Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Parse Json on ajax success [duplicate]

Tags:

json

jquery

ajax

I trie to get an json in my jquery ajax successe: to worke but i dose not.......

Thats 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

the php echos this:

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

Whats wrong with this? Thanks for helping!!!!

like image 768
user1606423 Avatar asked Jul 05 '13 20:07

user1606423


2 Answers

You need to parse your json before using it,

You can add a dataType in your request - jQuery will parse your response json

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

Or, you can parse it yourself -

success: function(data){
    var json_x = $.parseJSON(data);
like image 172
Mohammad Adil Avatar answered Nov 08 '22 08:11

Mohammad Adil


You could try this:

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 the message 'error' from 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/

like image 27
Indra Avatar answered Nov 08 '22 07:11

Indra