Page 1 of 1

Using javascript to parse JSON arrays

Posted: Sat Feb 04, 2012 9:06 pm
by bowersbros
Okay, so i have roughly the following JSON being created via PHP
<?php

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


?>
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 :)

Re: Using javascript to parse JSON arrays

Posted: Mon Feb 06, 2012 12:07 am
by jacek
JSON is valid javascript code,so you can eval() it

Assuming your json string is in the variable responce
var json = eval(responce);

alert(json.s1);
alert(json.s2);
This would alert "name" followed by "name2"

It's generally considered a good idea to use
var json = eval("(" + responce + ")");
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.

Re: Using javascript to parse JSON arrays

Posted: Mon Feb 06, 2012 12:10 am
by bowersbros
I decided to go with xml instead ;D