Patrick Patrick - 6 months ago 22
PHP Question

Javascript run php file and then download file

I have a page where I would like a form to be completed , a javascript file verifies the information, sends the information to a php file to mail it to me and then initiates a download.
The problem is that I can have the javascript file either send the mail or allow the file to be downloaded, but not both.

The code in question looks like this:

else {
document.dlform7.action = "http://www.myurl.com/c/post7.php" ;
document.dlform7.submit();
window.location.assign(url);
}


Is there a way (perhaps using load) that I can have both of these actions take place at once?

edit:

ajax option:

else {
$.ajax({
url: "http://www.myurl.com/c/post7.php";
type: "POST",
data: data,
cache: false,
success: function () {
window.location.assign(url);
document.dlform7.submit();

},

Answer

I think that you need to adjust the submit handler for your form. IRC, the submit event will cause the page to reload.

You will want to create an submit event handler for the form that will make an ajax call to your php script. Then have it return false to prevent the page reload. You should then be able to cause the file download at the same time.

UPDATE

If you want to download the file no matter what happens with the php script to send the email you can do the following:

else {
 $.ajax({
    url: "http://www.myurl.com/c/post7.php";
    type: "POST",
    data: $(document.dlform7).serialize(),     
    cache: false,
  });
  window.location.assign(url);

The ajax method is the form submission. It doesn't break the flow of your code so the redirect would happen after the request. (I am pretty sure that this will work).

If you want to wait until the php script successfully runs then you would move the code into the success callback like so:

else {
 $.ajax({
    url: "http://www.myurl.com/c/post7.php",
    type: "POST",
    data: $(document.dlform7).serialize(),     
    cache: false,
    success: function () { window.location.assign(url); }
  });

Of course, you could also just change the php page to send an email and then respond with the file that you want to download as mention in the comments.

Comments