March 3, 2012

How get data with jQuery.parseJSON

Question by Petr Šrámek

In page 1 I have this array:

$pole = array("countLike" => "countLike", "Message" => "Some message");
echo json_encode($pole);

And I want get this data on page 2, but this code doesn’t work.

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {
        var obj = jQuery.parseJSON(data);
        $(".countLike#"+id).html(obj.countLike);
        $(".Message#"+id).html(obj.Message);
    });
} 

Can you help me please with this code.
Thanks.

Answer by Starx

Pass json as expected output from the post request.

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {

        //data is already a json parsed string

        $(".countLike#"+id).html(data.countLike);
        $(".Message#"+id).html(data.Message);
    }, "json"); // <<<<< This is what you missed
} 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!