Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to read 'echo json_encode( )' from JQuery

I am using: echo json_encode($Response); to send an Associative array back to JQuery Ajax. Whenever I try to read each ID key value I get an undefined value. Please help me figure out what I am doing so wrong... Thanks in advance

My PHP Code:

$Stuff = 'Hello world';

$Success = true;
$Content = $Stuff;

$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);
# #

My JS code:

var sFirstName     = $('#student_first_name').attr('value');  

$.ajax({  
    type: "GET",  
    url: "../pgs/UpdateEditAStudent.php", 
    data: "FirstName="+ sFirstName ,  

    //The below code will give me: {"Success":true,"Content":"Hello world"}
    success: function(data){$("#Ajax_response").html(data);}

    //The popup window will show me "Undefined"
    //and: {"Success":true,"Content":"Hello world"}
    success: function(data){$("#Ajax_response").html(data); alert(data.Content);}
});  
like image 394
SirBT Avatar asked Jul 06 '11 15:07

SirBT


2 Answers

You should set the mime type aswell, wich, according to this question is application/json. Then jQuery will understand the answer is a json element. To do it, you'd do the following:

header('Content-Type: application/json');

In your UpdateEditAStudent.php before printing anything.

like image 110
Lumbendil Avatar answered Sep 22 '22 01:09

Lumbendil


You don't have to add a header to the PHP file, just use this Jquery parseJSON function:

Keep this PHP code as it is:

$Stuff = 'Hello world';

$Success = true;
$Content = $Stuff;

$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);

And for the JS:

$.ajax({  
    type: "GET",
    url: "../pgs/UpdateEditAStudent.php",
    data: "FirstName="+ $('#student_first_name').val(),

    success: function(data){
        // Here is the tip
        var data = $.parseJSON(data);

        alert(data.Content);
    }
});
like image 43
Anthony Simmon Avatar answered Sep 21 '22 01:09

Anthony Simmon