mpgn
mpgn

Reputation: 7251

Jquery and ajax How to parse json?

I'm using Jquery and ajax.

I have a simple form and my jquery :

This is a piece of the code :

username = $('input[name="username"]').val(); 
$.post("api.php", {username: username}, function(data) {  
    if(data == "error") {
        data("erreur");
    } else {
        alert(data);
        $('input[name="subscribers"]').attr("placeholder", "something").blur();
        $('input[name="viewCount"]').attr("placeholder", "something").blur();
    }
});

And the result of alert(data);

{"total":"628729","abo":"1646"}

I would like to put the result of total and the result of abo into my placeolder :

$('input[name="subscribers"]').attr("placeholder", ?abo?).blur();

But i don't know who to recover the result of the json and take the value of total and abo

note : my json is genrate by the file api.php with json_encode

Upvotes: 0

Views: 86

Answers (4)

Anthony Grist
Anthony Grist

Reputation: 38345

JSON is a string representing (in this case) an object, so data is a string. In order to go from the string to the object you need to parse it. There's a JSON.parse() function to do that:

if(data == "error") {
    data("erreur");
} else {
    alert(data);
    var yourObj = JSON.parse(data);
    $('input[name="subscribers"]').attr("placeholder", yourObj.abo).blur();
    $('input[name="viewCount"]').attr("placeholder", yourObj.subscribers).blur();
}

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115272

You can use $.parseJSON() to parse json

username = $('input[name="username"]').val(); 
$.post("api.php", {username: username}, function(data) {  
    if(data == "error") {
        data("erreur");
    } else {
        alert(data);
        data=$.parseJSON(data); // add this line
        $('input[name="subscribers"]').attr("placeholder", "something").blur();
        $('input[name="viewCount"]').attr("placeholder", "something").blur();
    }
});

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

Try this:

if (data) {
    data = JSON.parse(data);
    $('input[name="subscribers"]').attr("placeholder", data.abo).blur();
}

Upvotes: 0

Quentin
Quentin

Reputation: 944426

jQuery appears to be trying to handle your JSON as text (or, more likely, HTML).

Tell jQuery that it is JSON:

<?php header("Content-Type: application/json"); ?>

Then you can just:

foo = data.total

Upvotes: 1

Related Questions