D.Doe D.Doe - 1 month ago 4
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.

HTML CODE

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


JS CODE

$(function(){
var button = $('#submit');
button.click(function(){
alert("You clicked!");
getdata();
});

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


ajax.php

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

SOME CODE HRER;

$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

<?php
SOME CODE HRER;

$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

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

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