I'm pretty sure this shouldn't be as hard as it is. I have a form that runs the following function onsubmit:
function FORMVALIDATE_add_rota_entry() {
var rota_date = $("#rota_date").val();
var rota_id = $("#rota_id").val();
var am_pm = $("#am_pm").val();
if(rota_date == "")
{
alert("Please enter a date.");
return false;
}
if(rota_id == "error")
{
alert("Please select a rota from the list.");
return false;
}
// check if that rota has already been entered for that date and am/pm
$.ajax({
async:false,
type:"POST",
url:"/modules/rotas/check_rota_entry_existence",
data:{rota_date:rota_date, rota_id:rota_id, am_pm:am_pm},
success: function(result) {
if(result != "0")
{
alert("This rota has already been added to this date, "+am_pm+".");
return false;
}
}
});
}
It's called in the form tag by the following:
onsubmit="return FORMVALIDATE_add_rota_entry();"
And it works fine on the first two, rota_date and rota_id, with the alerts coming up when they should and it stopping the form from submitting but when it get's to the ajax call, it makes it fine, returns the right result, alerts when it should, but the return false doesn't seem to be stopping the form from submitting. Does anyone have any ideas because I'm stumped!
Thanks!
Try using
event.preventDefault()
just before thereturn
statement.Ok, so after trying the above solutions with no absolute success I came upon my own. I ditched the form element entirely and sent the three values onclick as below:
Then, the function became as follows:
All is works as it should!
Thanks for everyones input :) }
Remove:
Below your function add (where
my-form
is the id of the form):Change:
to:
And in your function change:
to
This will not always halt the form submission as the ajax request is asynchronous and code inside will not run in time to halt the form process.
Rather than using
try using
You might need to add
return true;
at the end of your function.youre doing it incorrectly. The way you are doing it, you should let the function return false always:
the only purpose the
return false;
in the if statements serve it to prevent the ajax code from running. But there should be one at the end of the function too. This should be an easier fix tho:onsubmit="FORMVALIDATE_add_rota_entry();return false;"