Php json_encode does not return the correct json encoding

I use a jQuery ajax call that accepts a json response:

var posturl = '/admin/getparamdetails/'; var data = "adnetworkId="+adnetworkId; $.ajax({ type: "POST", url: posturl, data : data, datatype: "json", success: function(msg){ //$("#displayPramForm").html(msg); //alert('hello'+msg.length+' '+msg.hello.length); console.log(msg); if(msg!='') { alert(msg.hello); } }, failure: function(msg){} }); 

in my php backend function, I use json_encode on a simple array, as shown:

  $json_encoded_string = json_encode(array("hello"=>'abc')); echo $json_encoded_string; die; 

but alert (msg.hello) returns undefined for me. What's going on here? Also, in my console.log, I can get the output as:

 {"hello":"abc"} 
+3
source share
2 answers

Use parseJSON for the returned data:

 if (msg) { msg = $.parseJSON(msg); alert(msg.hello); } 
+2
source

you need to send the data as a Content-Type "application / json", otherwise it will not work.

Just add the following to your PHP file:

 header('Content-type: application/json'); 
+1
source

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


All Articles