Skip to content
Advertisement

Really strange Javascript / PHP Behavior

from a webpage, I want to allow users to create a cvs file on the server and download it, generated by PHP ( header(‘Content-Description: File Transfer’) ).

function download_csv_file(){document.location='?action=download_file';}

It works like a charm. File is created and download start automatically like it should be.

But, if I add any other js events/scripts in the JS function (on the same line on a new line), the file is created on the server, but no download.

Really strange, a simple comment on the next line break the process too… But if the comment is on the same line, it works ! Crazy !!!

function download_csv_file(){
   document.location='?action=download_file';
   // Simple comment
}

Don’t work !

function download_csv_file(){
   document.location='?action=download_file'; // Simple comment
}

Works !!!

But if I add real code on the same line (instead a comment) it doesn’t work.

Any explanation or idea what I can try or search for ?.. Same behavior in Chrome and Firefox

Advertisement

Answer

 document.location

tells the browser to go to a different URL. Therefore it stops executing anything at the current URL and navigates to a new one instead. And of course that means that any JavaScript code following that command will be ignored.

N.B. since your new URL happens to download a file, it may be that you can still see the previous page in the background, which may lead you to believe that it’s still the current page.

You can potentially get round this by using window.open to visit the download URL in a different tab instead.

P.S. Regarding the issue with comments…did you check for any errors in your browser’s Console when that occurred? I can’t reproduce the problem: https://codepen.io/ADyson82/pen/dyGYQrd

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement