D.Doe
D.Doe

Reputation: 23

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!

Upvotes: 1

Views: 113

Answers (2)

adeneo
adeneo

Reputation: 318182

You have to prevent the form from submitting, and actually send the file.

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

and then

$(function(){
    $('#myForm').on('submit', getdata);
});

function getdata(e){
    e.preventDefault();

    function onDataReceived(data) {
        alert("Get the data!");
    }

    $.ajax({
        url         : "ajax.php",
        method      : 'POST',
        contentType : false,
        processData : false,
        data        : new FormData(this),
        dataType    : 'json',
        success     : onDataReceived
    });
}

Upvotes: 1

Marc B
Marc B

Reputation: 360572

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....
);

Upvotes: 3

Related Questions