Page 1 of 1

JSON Question.

Posted: Mon May 21, 2007 6:00 pm
by JellyFish
How do I have php return a JSON object?

I have:

Code: Select all

	while ($rows = mysql_fetch_array($results))
	{
		foreach($rows as $key=>$val)  $arr[] = "\"$key\":$val";
		echo '{'.implode(', ', $arr).'}';
	}
It returns the right format: {key: value, ...}

What can I do with this on the Javascript side?

Every time I have my request like this:

Code: Select all

	$.post(location.href,{action: "select",title: $("li.selected").text()},function (data) {
		data = eval('('+data+')');
		
		$("#title").removeAttr("disabled");
		$("#imageFile").removeAttr("disabled");
		$("#artical").removeAttr("disabled");
		$("#submit").removeAttr("disabled");
	});
The lines after "date = eval..." doesn't appear not to execute.

How could I take the response string from PHP and turn it into a JavaScript obj?

Thanks for reading I appreciate some help with this one. :D

Posted: Mon May 21, 2007 6:47 pm
by smudge
May i suggest the Prototype JS Library? I believe the newest version has functions like you are using (ie: $()) and also has JSON -> JS and JS -> JSON support, as well as many other useful features like AJAX functions. I use it just about everytime i have to do DHTML.

Re: JSON Question.

Posted: Mon May 21, 2007 7:29 pm
by bdlang
JellyFish wrote:How do I have php return a JSON object?
...

How could I take the response string from PHP and turn it into a JavaScript obj?
You can try the JSON PECL extension, which is innate to PHP > v5.2, or possibly use one of the classes available online. I myself have used the former with success.

Google Search: PHP JSON class

Posted: Mon May 21, 2007 9:34 pm
by JellyFish
I found that extension but I don't know how to install extensions for php (using a hosting service).

Prototype... Doesn't jQuery have the same abilities?


Besides all this I figured it out.

Thanks for the post anyways guys.

Posted: Tue May 22, 2007 1:46 am
by Kieran Huggins
pssst - http://json.org has really simple documentation.

One snag to watch out for is putting double-quotes around your strings - that will likely solve your problem.

Posted: Tue May 22, 2007 2:52 am
by JellyFish
Thanks. :D