Stefan
Stefan

Reputation: 155

Output JSON encoded array through Jquery

I have a single json encoded array set in an ajax call:

 $var = json_encode($_SESSION['pictures']);

I put this json encoded array in a var called "array" When I alert the var array, I receive the following callback:

  ["http://linktoimage1", "http://linktoimage2"]

now I want to output the first value through a jquery call:

 $('#imgswap').attr('src', array[0]);

When I make this jquery call, I receive the value "[". If I change it to array[2], I receive "h". So he's giving me back characters instead of the complete values of the array.

What am I doing wrong?

Upvotes: 0

Views: 1029

Answers (3)

Musa
Musa

Reputation: 97672

You need to parse the json in order to make it an array otherwise its just a string

array = $.parseJSON(array);
$('#imgswap').attr('src', array[0]);

Also you can have jQuery.ajax parse it for you if you set the dataType to json

Upvotes: 3

Linuxios
Linuxios

Reputation: 35783

Change your last line to this:

$('#imgswap').attr('src', JSON.parse(array[0]));

You need to parse your JSON. If you don't do that, you have a string, not an array.

Upvotes: 0

jeff
jeff

Reputation: 8338

You're receiving your data as a string rather than as actual JSON. Are you using dataType: text in your AJAX call? If so, either omit that line or replace it with dataType: json.

Upvotes: 0

Related Questions