Using javascript to parse JSON arrays

JavaScript related questions should go here.
Post Reply
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Using javascript to parse JSON arrays

Post by bowersbros »

Okay, so i have roughly the following JSON being created via PHP

[syntax=php]<?php

$array = array('s1' => 'name','s2' => 'name2'); // etc

$arrayJSON = json_encode($array);


?>[/syntax]

I need help finding a way to call a PHP page with 1 parameter using AJAX, and return a JSON array back, and from there I need to be able to parse it using javascript / jquery.

The basis behind this, is that one option is chosen, and the next one loads without reloading the page (like, from a checkbox or dropdown list etc)

Thanks :)
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Using javascript to parse JSON arrays

Post by jacek »

JSON is valid javascript code,so you can eval() it

Assuming your json string is in the variable responce

[syntax=javascript]var json = eval(responce);

alert(json.s1);
alert(json.s2);[/syntax]

This would alert "name" followed by "name2"

It's generally considered a good idea to use

[syntax=javascript]var json = eval("(" + responce + ")");[/syntax]

as it can fail for mismatched ( otherwise.

You will read a lot about not evaling form unsafe sources. php's json_encode() is a safe source so it's fiine to do this.
Image
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Using javascript to parse JSON arrays

Post by bowersbros »

I decided to go with xml instead ;D
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
Post Reply