简体   繁体   中英

PHP not working when called on from JS

I am new to everything Javascript and PHP so I will try to be as clear as possible.

I have written a PHP file, which is working perfectly when I open it directly in my browser. However when I call on the PHP file from my JS , it doesn't work.

This is the PHP:

<?php
// remove the headers at start for a reset
header_remove("Content-type");
header_remove("Content-Disposition");

// here comes everything that will be in $myfile

header("Content-type: application/gpx+xml");
header("Content-Disposition: attachment;Filename=route.gpx");

echo $myfile;

?>

This is what I am using to call the PHP file in JS:

function fuDownload(){

$.get('phpfile.php');
}

The fuDownload function is called when clicked on a button.

http://api.jquery.com/jQuery.get/

jQuery.get( url [, data ] [, success ] [, dataType ] )

$.get( "test.php" ); requests the test.php page, but ignore the return results.

use $.get( "test.php", function( data ) { ... } ) , $.get( "test.php" ).done(function( data ) { ... }); or $( "#result" ).load( "test.php" ); ( http://api.jquery.com/load/ )

If your trying to generate a file using headers then $.get isn't the right function.

Try:

  window.location.href = 'phpfile.php';

You should use $.get to interact with the DOM at add elements to it, but header() must be called before any actual output is sent, which in your case ( assuming your just trying to automatically start a download) a standard link will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM