I am sending an email in jQuery and PHP, i need to tell the page to submit if the ajax was successful and don't submit if not. I have tried to place the return values in the success and error attributes, but that did not work, so i want to see if i could set the form to not send by returning false but if it was successful letting it submit the page for some server side work.
In the example below i have tried to set a variable and used a conditional to read it. I get an error message because the value does not seem to get passed globally, so when the conditional reads sendMe, it says it is undefined.
Is there a way to do this correctly?
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
var sendMe = 'true';
},
error: function(){
alert('Error: Message could not be sent');
}
});
if (sendMe == 'true'){
//Submit the page...
}
else {
return false;
}
just create a sendMe()
function, and call that function from success:
That should do the trick.
The reason your code does not work is because the javascript is not waiting for the ajax call to come back, right after the ajax call it evaluates sendMe which at that point is still false.
You could consider doing this call synchronously of course to prevent that, but I am not sure that is the right way to go. ( async : false
is deprecated as of jQuery 1.8 )
When is your conditional if(sendMe == 'true') ... ever getting called?
make a little function like this:
function sendMe(){
// whatever your form's id is, put it in place of myForm
$("#myForm").submit();
return true;
}
and in your ajax success block call the function
Try using this setup:
var form = this;
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
form.submit(); // submit form, bypassing jQuery events
},
error: function(){
alert('Error: Message could not be sent');
}
});
return false; // prevent submit
By returning false after the ajax request, we prevent the submit, then we directly submit the form bypassing all of jQuery's submit handlers using form.submit();
Set the form to go through a validator method on submit event:
<form onSubmit='return checkForm();'> </form>
In this method - checkForm()
- perform your ajax post normally. If the ajax post returns as 'success' proceed with the submit else use return false;
to cancel submit and notify the user accordingly.