hi again,

i'm wondering if it's possible to return an array from my php generated content to ajax's responseText. I tried echoing back the whole array variable but can't seem to fully receive it in javascript.

somewhere in file1.php

<?php
$myArray = array();

$myArray = "ajax tech";
$myArray = 20;

echo $myArray;

?>


somewhere in the page that i need the data to display :

//(javascript, ajax = xmlHttp)

var myArray = new Array();
myArray = xmlHttp.responseText;

alert(myArray); //will alert 'Array'

alert(myArray[0]); //alerts 'undefined'

Recommended Answers

All 12 Replies

Eek.. again you need a way of determining IN JAVASCRIPT what the contents of a response represent. Semantically, there is no difference between an echoed PHP array and a line of plain text. All you are doing at the moment is reading the response text ( a string ) and trying to implicity cast it to a javascript array - this won't work.

When PHP echoes an array, it just prints out text to be output at the browser; at the javascript end you'd need to interpret that array using text manipulation functions or some other processing method, in order for that plain text to be a meaningful javascript array.

Just remember, the output from a typical server-side application doesn't have the same meaning as the running code that generated it; it has whatever meaning you choose to give it, but you have to choose how to deal with it, in order to give it any meaning atall.

That aside.. can you post the output from your PHP page? I'm not in the mood to run PHP code this morning, but I want to see how close to interpretable an array dump is..

do you mean the code that produces the output for javascript?

$user = null;

$userData = array();

try
{

    if(isset($_SESSION['name'])){
        $userData['name'] = $_SESSION['name'];
    }
    if(isset($_SESSION['userid'])){
        $userData['userid'] = $_SESSION['userid'];
    }

}   
catch(Exception $e)
{
 logger($e->getMessage());
 echo "Error : " .$e->getMessage();
}

echo $userData;

not much use, it just produces 'Array' plain text. If that's the case, do you mean i'll actually have to organise my own data into an understandable structure, and then chop it out from javascript and pass back to an array manually?

such as from php,

echo $myArrayStr = "name='mr box' | age=20 | sanity = 'not really' ";

then in javascript,

maybe some sorta split function that separates the "|" delimeter and assign them all into javascript?

Yes, that would work. You could also print output like this from PHP:

new Array( "Saab", "Volvo", "BMW" )

and then in javascript:

var myArray = eval( xmlHttp.responseText );

The eval function will treat the plaintext as javascript; returning an array type object in this case. That'd work for a numerically indexed array, you're using string indicies but you can use the same principle,

Don't use this principle the other way round whatever you do; that is, don't send textcode from client to server and evaluate it. That's the biggest security hole you could possibly make.

Hm. there are apparantly no constructors for key/value type arrays ( hashes/dictionaries/w.e. you'd call them )

This might help you:

<html>
<body>

<script type="text/javascript">
function mkhash( )
{
  var ret = new Object( );
  for (var i = 0; i < arguments.length; ++i )
  {
    ret[arguments[i][0]] = arguments[i][1];
  }
  return ret;
}

var myhash = eval( 'mkhash( [ "name", "matt" ], [ "age", "22" ] )' );

document.writeln( myhash[ "name" ] );
document.writeln( myhash[ "age" ] );
</script>

</body>
</html>

As long as you print out a call to mkhash from PHP, i.e.:

echo "mkhash( [ 'name', 'mr box' ], [ 'age', '20' ], [ 'sanity', 'not really' ] )";

when you eval that in javascript, js will 'find' the mkhash function if it's present on the page, and use that to generate the key-value type array object.

Alternatively, if you just print:

[ 'name', 'mr box' ], [ 'age', '20' ], [ 'sanity', 'not really' ]

from PHP, you can then evaluate it like:

var myhash = eval( 'mkhash('+xmlhttp.responseText+')' );

and then use name-based indexing in JS. Note, that works because [ "a", "b".. etc ] is a shorthand constructor for a javascript array - in this case you're only using them to indicate the key/value pairs in a hash.

good luck, anyway.

Actually, it seems that there are shorthand key/value array constructors; and this is what digital-ether suggested in your other thread of this nature: http://en.wikipedia.org/wiki/JSON. That format is directly interpretable by javascript.

> it seems that there are shorthand key/value array constructors
Actually it's called an 'object literal'.

Encode the data you want to send by using a PHP binding for JSON at the server and decode the same using Douglas Crockfords' Javascript library for JSON.

Thanks guys, i'll try this up.

Is JSON widely used? I'm trying to use pure javascript without importing any third party components though, unless necessary.

Well, data in that JSON format is valid, runnable javascript; the libraries that ~s.o.s~ suggests are just helper utilities.

A client-side library for interpreting the JSON safely is a good idea; since it's not totally safe to run code that you can't guarantee hasn't been tampered with.

thanks guys, after trying out few suggested methods here, jSON is the most superior method since it takes into consideration strings with quotes.

S.O.S, why am i able to decode the encoded json string directly using eval without Douglas Crockfords' Javascript library for JSON. ?

on my php, im just using simple json_encode($mydata);

on javascript, myData= eval("(" + xmlHttp.responseText + ")");

◄ S.O.S, why am i able to decode the encoded json string directly using eval without Douglas
◄ Crockfords' Javascript library for JSON. ?

This is because Crockford's library is not mandatory. It is more of a convenience library providing 'safe eval'. I hope you do realize that eval can execute any arbitrary piece of Javascript code. This is a major security issue if someone manages to inject a malicious script in your code. Crocford's library makes sure that doesn't happen by looking for malicious patterns.

Plus, how do you propose to encode Javascript objects and send them to your server in JSON. Converting Date objects to JSON format is a royal pain. I would recommend you to take a look at the Javascript library for JSON to understand it's full implications and the benefits it can bring.

It's Very Simple........

In PHP Script

merge the array elements to string seperated by commas.

print explode(',',$arrayname);

In Javascript

Reverse Process.

s = xmlhttp.responseText;
customarray = s.split(",");

Now your javascript array ready for use.

by

Vannakkudi Saravanan

and don't need to create array you can use:
in php:

echo $_SESSION['name'] . ',' . $_SESSION['userid'];

in js:

s = xmlhttp.responseText;
customarray = xmlhttp.responseText.split(",");

by

Vannakkudi Saravanan :))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.