D.Doe D.Doe - 11 months ago 37
Ajax Question

Why can't I get json data in JS from PHP?

I'm trying to upload a file and get some processed data from it by PHP,but I came across some problems. Here are my simplified codes.


<form action="ajax.php" method="post" enctype="multipart/form-data">
<input type="file" name="mypic">
<input type="submit" value="upload" id="submit">


var button = $('#submit');
alert("You clicked!");

function getdata(){
function onDataReceived(data) {
alert("Get the data!");
url : "ajax.php",
method : 'GET',
cache : false,
dataType : 'json',
success : onDataReceived


$filepath = $_FILES["mypic"]["tmp_name"];
$filename = $_FILES["mypic"]["name"];


$mech_para = "Hello";
$json = json_encode(array("mech_para"=>$mech_para));

echo $json;

Once I clicked the submit button, the page will jump to ajax.php, and it shows {"mech_para":"Hello"}, but without the alert:Get the data!.

But if I delete the first two lines in the ajax.php as below


$mech_para = "Hello";
$json = json_encode(array("mech_para"=>$mech_para));

echo $json;

The result turns to be totally fine, the page jump to ajax.php and shows the right data, and the alert(Get the data!) also shows.

I don't know what causes this result and how to solve it, I wander if there is any conflicts between ajax and the GLOBAL VARIABLE _FILE, OR if there is any other way that I can both process the file and return the data I want to JS.
Very thanks!

Answer Source

Because you're simply ASSUMING success. You told jQuery to expect JSON, and what you're sending out is almost certainly NOT json.

You're doing a GET request, which means it's IMPOSSIBLE for $_FILES to contain anything. That means you're generating PHP warnings for undefined indexes

You have no error handler on your jquery call, so jquery can't even tell you that it failed to decode this (corrupt) json it received.

Never EVER assume success when dealing with external resources. Always assume failure, check for failure, and treat success as a pleasant surprise. That means you need to have

   error : function(jqerr, msg) {
      alert('ajax request failed: ' + msg);