John x
John x

Reputation: 4031

parse json sent by php using jquery

my question may be the duplicate of many questions but i have tried all my options but couldn't get to parse the json that i receive via an Ajax request

hi,

so im getting this json response as a result of Ajax call

{
    "audi": [
        "100",
        "200",
        "80",
        "90",
        "a3",
        "a4",
        "a6",
        "a8"
    ]
}

this is the json i am receiving following is my one of the attempted options

var obj = JSON.parse(html);
            alert("json decoded");

            for(var yahoo in obj)
            {
             alert(obj[yahoo]); // this line gives me 100,200,80,90,...
            }

any help is much appreciated ...

EDIT:

here is my ajax call

 $.ajax({
            url: "makemodel.php",
            type: "POST",
            data: {data:data},
            cache: false,
            async:false,
            dataType:'json',
            success: function (html) {           
            alert("success");           
            var obj = JSON.parse(html);
            alert("json decoded");          
            for(var yahoo in obj)
            {
             alert(obj[yahoo]);
            }

                      }//ajax success ends
           });//ajax ends

Upvotes: 2

Views: 3788

Answers (3)

Sharp Coders
Sharp Coders

Reputation: 458

You can also get your json data using getJSON, following is the example.

var price = 0;
$.getJSON("make_model.php", {data: data}, function(response){
    $.each(response, function(key, value){
        price += value['price'];
    });
});
alert(price);

Upvotes: 1

phihag
phihag

Reputation: 287785

If you set the dataType option of jQuery's ajax call to "json", jQuery will automatically parse the JSON code. The first argument to your success callback is already the parsed object then.

success: function (data) {   
   var s = 0;
   for (var i = 0;i < data['audi'].length;i++) {
       s += parseInt(data['audi'][i]);
   }
   alert("Sum of all audi prices: " + s);
}

Upvotes: 3

dmies
dmies

Reputation: 1

Maybe, this code can help you, too:

var obj = jQuery.ajax({
   url: url,
   async: false,
   dataType: 'json'
}).responseText;

for(var yahoo in obj){
   alert(obj[yahoo]);
}

Upvotes: 0

Related Questions