views:

92

answers:

2

Hi, Here in an array i have in javascript, this works great!

_rowData: [
    { name: "Most Recent", view: "recentView" }, 
    { name: "Most Popular", view: "popularView" }, 
    { name: "Staff Picks", view: "staffView" }
],

How could i generate this array from a php script? I want to use AJAX to get the results returned by the php.

Thanks!

EDIT How do i manipulate this php returned json, back into _rowData ?

+9  A: 

Try to use JSON. PHP function json_encode()

EDIT: Code example(server side - PHP):

  // data handling
  $arrayToSend = array(array('name'=>'Most Recent', 'view'=>'recentView'),
                       array('name'=>'Most Popular', 'view'=>'popularView'),
                       array('name'=>'Staff Picks', 'view'=>'staffView'));

  echo json_encode($arrayToSend);

Client side(javascript). Note: YUI is used to show client-side handling:

var callback = {success: function(req) {
                            selectItems(req.responseText);
                         }
                };
YAHOO.util.Connect.asyncRequest('GET',url + '?param=1',callback);

function selectItems(resp) {

  var result = eval('(' + resp + ')');

  for (var i=0; i < result.length; i++) {
    // Do whatever you want with array result :)
  }
}

Comments: 1) In PHP script you have to make response, which outputs your array, previously encoded to JSON format. 2) Except YUI you can also use any appropriate JavaScript library to generate AJAX request(i.e. JQuery, Prototype). In my case, I used function eval() to make array from JSON response.

Hope, it'll help you.

Alex
could you add in some sample code, im a bit confused :(
tarnfeld
+3  A: 

json_encode() example:

<?php
$data = array('name' => 'Imran', 'age' => 23);
echo json_encode($data);
?>

outputs

{ 'name': 'Imran', 'age': 23 }
Imran