vote up 1 vote down star

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 ?

flag

2 Answers

vote up 9 vote down check

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.

link|flag
could you add in some sample code, im a bit confused :( – tarnfeld Dec 28 at 11:12
vote up 3 vote down

json_encode() example:

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

outputs

{ 'name': 'Imran', 'age': 23 }
link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.