The correct way to read 'echo json_encode ()' from jQuery

I use: echo json_encode ($ Response); send associative array back to jQuery Ajax. Whenever I try to read each value of an ID key, I get an undefined value. Please help me figure out what I'm doing wrong. thanks in advance

My PHP code is:

$Stuff = 'Hello world'; $Success = true; $Content = $Stuff; $Response = array('Success' => $Success, 'Content' => $Content); echo json_encode($Response); 
# #

My JS code is:

 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);} }); 
+6
source share
5 answers

You should also set the mime type, which, according to this question , is application/json . Then jQuery will understand that the answer is a json element. To do this, you must do the following:

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

In UpdateEditAStudent.php before printing nothing.

+9
source

You do not need to add a header to the PHP file, just use the jquery parseJSON function :

Save this PHP code like this:

 $Stuff = 'Hello world'; $Success = true; $Content = $Stuff; $Response = array('Success' => $Success, 'Content' => $Content); echo json_encode($Response); 

And for 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); } }); 
+4
source

You need to determine the correct dataType or provide the correct header as described by Lumbendil.

You can manually define dataType on json , so your code will look like this:

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

This is an array. You should probably make a warning (data ['Content']);

+1
source

do something like that

 $Stuff = 'Hello world'; $Success = true; $Content = $Stuff; $Response = array('Success' => $Success, 'Content' => $Content); echo json_encode($Response); 
0
source

Source: https://habr.com/ru/post/892151/


All Articles