simPod
simPod

Reputation: 13456

Getting JSON encoded variables from php

i have this php code:

$query = mysql_query("SELECT * FROM table WHERE id=$id");
while($item = mysql_fetch_assoc($query)){
    $dataArray['var1'] = $item['var1'];
    $dataArray['var2'] = $item['var2'];
    $dataArray['var3'] = $item['var3'];
    array_push($return_arr,$dataArray);
}

echo json_encode($return_arr);

it's in my ajax.php file

Then I'm using jquery to send there id via ajax request:

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'id='+id,
    success: function(data) { 
        alert(data);
    }
 });

and it alerts me this: [{"var1":"somevarhere","var2":"somevarhere2","var3":"somevarhere3"}]

can someone tell me please how I can access for ex. var3 to get somevarhere3?

thanks

Upvotes: 1

Views: 2649

Answers (3)

simPod
simPod

Reputation: 13456

Ok, I found the solution. Thanks to Pascal MARTIN I got the idea to parse the result so I used this:

data = data.substring(1,data.length-1);
data = $.parseJSON(data);
alert(data.var3);

first line removes [], second line parses JSON to Object, and third line accesses the property

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

According to the documentation of jQuery.ajax, the data it receives as first parameter is interpreted depending on the value of the dataType option passed to jQuery.Ajax.

What if you pass 'json' for that parameter ?
Like this :

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'id='+id,
    dataType: 'json', 
    success: function(data) { 
        alert(data);
    }
 });

Doing this, jQuery.ajax should interpret the data returned from the server as JSON.


Else, the documentation says that, if no dataType is specified (quoting) :

jQuery will try to infer it based on the MIME type of the response

So, the other solution would be to return some JSON content-type from the PHP code (see The right JSON content type?), with something like this :

header('Content-type: application/json');

Before doing the echoing.

And, again, jQuery.ajax should interpret the data returned from the server as JSON.

Upvotes: 4

Richard Dalton
Richard Dalton

Reputation: 35793

Should be able to access it like this:

data[0].var3

Where 0 is the index of the item in the array you want to access.

Upvotes: 0

Related Questions