Saturday, April 6, 2013

Passing a PHP array to a Javascript Ajax call

Recently, I found myself making an Ajax call to a PHP function and needing more than just one piece of data back from it.

For those who don't know, a PHP function can "return" data to an Ajax call by echoing the data out. So, for example, given this Ajax call:

  $.ajax({
      type: "POST",
      url: 'http://www.domainname.com/module/controller/insert',
      data: { name: 'Donna Oberes', address: 'The Universe' }
    }).done(function(msg) {});

And given a function that inserts data into the database, returning/echoing data would look like:

  public function insert($name, $address)
  {
    $new_id = 
      $this->people_model->insert(array('name' => $name, 'address' => $address));
    
    // Return the ID by echoing
    echo $new_id;
  }

The calling Ajax function will 'catch' $new_id with the variable msg and do whatever it wants with it.

But how about if I need more than just the new_id? Say, for example, I need the new id and a nicely formatted date of when this new id was created. I have to return these through an array, but the key is to return the array json_encoded. So I should do this:

 
  public function insert($name, $address)
  {
    $new_id = 
    $this->people_model->insert(array('name' => $name, 'address' => $address));
    $data = array('id' => $id, 'date' => 'April 6, 2013'); 
    echo json_encode($data).
  }

And then in the ajax call that catches the printout, msg will catch the array, but the array has to go through $.parseJSON so that it's usable as a JavaScript array.

  $.ajax({
      type: "POST",
      url: 'http://domainname.com/module/controller/insert',
      data: { name: 'Donna Oberes', address: 'The Universe' }
    }).done(function(msg) {
      var obj = $.parseJSON(msg);
      // Print out
      $('#student_list').append("New student ID " + obj.id + " added on " + obj.date);
    });

No comments:

Post a Comment