Passing a PHP associative array to JavaScript

B

bruce

How do I parse a PHP associative array with JavaScript?

I want to returning from the server some database elements using
AJAX.

1. Will AJAX allow my to return to a PHP associative array?

2. If so, how do I retrieve the data,ie parse the array into
elements? Would it be any better to return an indexed array?

Thanks for the help...

Bruce
 
R

RobG

How do I parse a PHP associative array with JavaScript?

I want to returning from the server some database elements using
AJAX.

1. Will AJAX allow my to return to a PHP associative array?

2. If so, how do I retrieve the data,ie parse the array into
elements?  Would it be any better to return an indexed array?

<URL: http://www.json.org/ >
 
R

Ross McKay

How do I parse a PHP associative array with JavaScript?

You are best served by turning the array into something that JavaScript
can handle, e.g. XML or JSON.

http://en.wikipedia.org/wiki/XML
http://en.wikipedia.org/wiki/JSON
I want to returning from the server some database elements using
AJAX.

1. Will AJAX allow my to return to a PHP associative array?

2. If so, how do I retrieve the data,ie parse the array into
elements? Would it be any better to return an indexed array?

Unless your PHP is providing data to other clients, I'd return the data
as JSON to make it easy to deal with in JavaScript. PHP has a function
to convert data into JSON:

http://au.php.net/manual/en/function.json-encode.php

And there's plenty of options for parsing the JSON in JavaScript:

http://json.org/
https://developer.mozilla.org/en/JSON
 
B

bruce

You are best served by turning the array into something that JavaScript
can handle, e.g. XML or JSON.

http://en.wikipedia.org/wiki/XMLhttp://en.wikipedia.org/wiki/JSON




Unless your PHP is providing data to other clients, I'd return the data
as JSON to make it easy to deal with in JavaScript. PHP has a function
to convert data into JSON:

http://au.php.net/manual/en/function.json-encode.php

And there's plenty of options for parsing the JSON in JavaScript:

http://json.org/https://developer.mozilla.org/en/JSON

Thanks...
json does the job..

Bruce
 
B

bruce

Thanks...
json does the job..

Bruce

Sorry, but now I'm having trouble retrieving the data..

This alert shows the complete array, correctly.
alert("detail Result: " + strResult);

Both of these alerts display: Undefined
alert(strResult['newspaper']);
alert(strResult.newspaper);

What am I doing wrong??
 
B

bruce

On Mar 7, 6:09 pm, Ross McKay <[email protected]>
wrote:
Thanks...
json does the job..

Sorry, but now I'm having trouble retrieving the data..

This alert shows the complete array, correctly.
alert("detail Result: " + strResult);

Both of these alerts display: Undefined
alert(strResult['newspaper']);
alert(strResult.newspaper);

What am I doing wrong??

I forgot to mention that strResult is returned from AJAX..
 
B

bruce

Sorry, but now I'm having trouble retrieving the data..
This alert shows the complete array, correctly.
alert("detail Result: " + strResult);
Both of these alerts display: Undefined
alert(strResult['newspaper']);
alert(strResult.newspaper);
What am I doing wrong??

I forgot to mention that strResult is returned from AJAX..

OKAY.. I figured it out.
var temp = "values = " + strResult;
eval(temp);
alert(values['newspaper']);
alert(values.newspaper);

This makes it work..

Thanks for all your help...

Bruce
 
R

Ross McKay

OKAY.. I figured it out.
var temp = "values = " + strResult;
eval(temp);
alert(values['newspaper']);
alert(values.newspaper);

Or you can do this:

var parseJSON = function(data) {
return window.JSON ? JSON.parse(data) : eval("(" + data + ")");
};

var values = parseJSON(strResult);

The eval() requires an expression, so wrapping your JSON packet in
parentheses allows eval() to ... um ... evaluate it :)

It's a little simplistic, but functional, and it will avail itself of a
built-in JSON parser on browsers that provide one.

You might like to load Crockford's json2.js to provide a JSON.parse
across browsers instead:

https://github.com/douglascrockford/JSON-js
 
B

bruce

OKAY.. I figured it out.
   var temp = "values = " + strResult;
   eval(temp);
   alert(values['newspaper']);
   alert(values.newspaper);

Or you can do this:

 var parseJSON = function(data) {
     return window.JSON ? JSON.parse(data) : eval("(" + data + ")");
 };

 var values = parseJSON(strResult);

The eval() requires an expression, so wrapping your JSON packet in
parentheses allows eval() to ... um ... evaluate it :)

It's a little simplistic, but functional, and it will avail itself of a
built-in JSON parser on browsers that provide one.

You might like to load Crockford's json2.js to provide a JSON.parse
across browsers instead:

https://github.com/douglascrockford/JSON-js

Thanks... I'm using your suggestion....

Appreciate the comeback...

Bruce
 
D

Denis McMahon

How do I parse a PHP associative array with JavaScript?

I want to returning from the server some database elements using
AJAX.

1. Will AJAX allow my to return to a PHP associative array?

2. If so, how do I retrieve the data,ie parse the array into
elements? Would it be any better to return an indexed array?

I normally pass these as a json string containing an object where
object.attribute = value

for example, in my php I can create the json text:

----8<----8<----8<----8<----
<?php
header("Content-Type: text; charset=utf-8");
$str = "{ 'title' : 'Mr' , 'firstnames' : 'john henry' , 'lastname' :
'smith' , 'height' : 180 , 'weight' : 110 }";
echo $str;
?>
----8<----8<----8<----8<----

Note that there is no blank line at the end of the file, and no "\n" is
used, just a single one line string.

Next, in javascript I can use an XmlHttpRequest(xhr) object to request
the php file from the server, which will get a text response back, and
in the xhr processing, eval the text response:

var thePerson = JSON.parse('(' + responseText + ')');

then, in javascript:

thePerson.title = 'Mr'
thePerson.firstnames = 'john henry'
thePerson.lastname = 'smith'
thePerson.height = 180 (cms I guess)
thePerson.weight = 110 (kgs I guess)

Note that JSON.parse may not exist in older browsers, so you can either
supply it, or use the dreaded eval instead. It also leaves out a lot of
the javascript surrounding the use of ajax and the xhr object.

Rgds

Denis McMahon
 
R

Ross McKay

It's not safe to test for native JSON support by testing for 'window.JSON'
existence, in order to avoid errors in older browsers. I prefer to use:

var rsp; // defined inside a function
if (typeof JSON !== "undefined") {
try {
// IE8, FF3.5, Safari4, Chrome4, Opera10.5
rsp = JSON.parse(data);
} catch (ex) { // alert('Error:\n\n' + ex.description); }
} else {
// suggested by http://tools.ietf.org/html/rfc4627
rsp = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
data.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + data + ')');
}

Fair point, but the OP is still probably better off using Crockford's
json2.js which deals with these issues, and more. As I stated:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top