views:

48

answers:

2

Hello guys,

I have to send mail before submitting my php page, I am submitting the page using javascript. my mail script is in sendmails.php file. so can I send an ajax request to send mail before submitting the page using java script ? like follows

function submit_page()
{
//trying to run send_mail.php
..............................//ajax codes
............................
xmlhttp.open("GET","send_mail.php",true);
xmlhttp.send();
.................................

if(a)
form.action = 'one.php'
else
form.action = 'two.php'
form.submit()//form submitting using javascript
}

Will it run the send_mail.php file in the server ?

Thank you

A: 

I doubt it - ajax requests take a certain amount of time to complete, and you're navigating away from the page immediately, which will interfere with the request.

Suggestion - do the ajax request in synchronous mode. That way you're guaranteed it will finish before the form submits.

Sam Dufel
So all requests that came from a page are aborted when the page is left?
Aaron Digulla
I believe so - I had a problem with the request being aborted on navigating away, but it also could have been because it was in an iframe. At the very least, though, it's not safe. There's a good chance you'll leave the page before the ajax request can even finish sending.
Sam Dufel
+2  A: 

Yes but don't rely on the fact that this happens before send() returns. send() just starts a background thread which will eventually open the connection to send_mail.php and post the form. So it can happen that the form is submitted before the mail is sent.

Aaron Digulla