JQuery Parse Json on ajax success

I am trying to get json in my jquery ajax successe: to work, but I do not overrun ........

Here is what I tried to do:

$("#addcatform").submit(function() { var str = $(this).serialize(); $.ajax({ type: "POST", url: "ajax.php", data: str, success: function(data){ var json_x = data; alert(json_x.firstName2); $('#result').html(json_x.firstName2); $('#result2').html(json_x.b); } }); return false; event.preventDefault(); }); // submit end 

php echos this:

 $arr = array ('firstName2'=>'hallo','b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); 

What is wrong with that? Thanks for helping !!!!

+4
source share
3 answers

You need to analyze your json before using it,

You can add dataType to your query - jQuery will parse your json response

 $.ajax({ type: "POST", url: "ajax.php", dataType: 'json', 

Or you can take it apart yourself -

 success: function(data){ var json_x = $.parseJSON(data); 
+8
source

You can try the following:

 var data=$.ajax({ type: "POST", url: 'ajax.php', data: { data:str }, async: false, dataType: 'json' }); var msg= data.responseText; msg=jQuery.parseJSON(msg); 

I usually send either an array or an error message on my php page

 if(msg=='error') { /* do something */ } else // use the data 

This works with jquery 1.6-> 1.8

EDIT: Since jquery 1.8 async is deprecated. I would recommend this format:

 $.ajax({ type: "POST", url: 'ajax.php', data: { data:str }, dataType: 'json', ).done(function(data) { // do something with the data }) .fail(function() { // give appropriate message }) 

http://api.jquery.com/jquery.ajax/

+2
source

data is the string in your example. Use jQuery.getJSON () . Edit: since you cannot execute a POST request using getJSON (dรปh), use .ajax with the appropriate data type. This will retrieve the data via ajax and parses the resulting string as if it were JSON. Even with getJSON result will be an array (or an array, such as an object, not sure). It has no methods or variables that you can access using dot notation. You need to access it through data['a'] .

 $.ajax({ dataType: "json", type: "POST", url: "ajax.php", data: str, success: function(data){ var json_x = data; alert(json_x['firstName2']); $('#result').html(json_x['firstName2']); $('#result2').html(json_x['b']); } }); 
0
source

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


All Articles