tags:

views:

29

answers:

2

hello sir, i just want to ask if how to return or how to call the returned arrays to the function..

this is my javascript

$(document).ready(function(){
alert(askServer());   

function askServer()
{
 var strUrl = "functions.php";
 var strReturn = new Array();

 jQuery.ajax({
  url:strUrl, success:function(html){strReturn = html;}, async:false
 });

 return strReturn;
}
});

and this is from my functions.php..

<?php
$dirArray = Array('data_1','data_2','data_3');
echo $dirArray;
?>

my problem is it will alert the word "Array"/...

can it be done like this?

alert(askServer()[0]);

to alert "data_1"?

A: 

You have several flaws here:

First you cannot assign strReturn this way because return strReturn; will be executed before the Ajax is finished (oh I see you have async: false but that is always a bad idea).

Second, you cannot just send an PHP array this way. It shows Array because this is what happens if you convert an array to a string.

Use json_encode() to transform the array to JSON:

<?php
$dirArray = Array('data_1','data_2','data_3');
echo json_encode($dirArray); // will now be '["data_1", "data_2","data_3"]'
?>

and on the client side do:

$(document).ready(function(){

askServer(function(data){
    alert(data[0])
});   

function askServer(callback)
{
    var strUrl = "functions.php";

    jQuery.ajax({
       url:strUrl, 
       success:callback, 
       dataType: "json" 
    });

}
});

This is what happens: You pass a callback function to askServer that should be executed once the Ajax request is complete. You specify that the response will be a JSON string so jQuery automatically transforms this into an Object/Array.

Felix Kling
thank you so much sir..
vrynxzent
A: 

Because you just can't echo Array.

There are three (probably even more:]) possibilites to interchange arrays (as logical structures) between PHP and JS:

1., explode on PHP side, implode JS routine in your page

explode takes values of array and glues them together with your string (i.e. 'GLUE'):

array('str1','str2') => 'str1GLUEstr2' with
implode('GLUE', $array);

2., JSON: read at http://www.json.org
3., XML: read at http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html

Adam Kiss