0

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

is it also possible to parse the array totally, for example var array = JSON.parse($var);, so that I can use only $('#imgswap').attr('src', array[0]); ??
@Musa: Didn't know JQ had a JSON method. I guess jQuery really does do everything...
0

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.

2 Comments

is it also possible to parse the array totally, for example var array = JSON.parse($var);, so that I can use only $('#imgswap').attr('src', array[0]); ??
@Stefan: Yes. You can definitely do that.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.