PHP, MYSQL, CSS, LINUX TUTORIALS

Using AJAX and PHP together

In this tutorial i’ll show you how to use PHP and AJAX together and get the results that you need.

Here’s an example of a function that executes a ajax request

View Code JAVASCRIPT
function execAjax(type){
   $.ajax({
      url: 'ajax.php?type='+type,
      dataType: 'json',
      success: function( data ) {
         var items = [];
 
         $.each(data, function(key, val) {
            items.push('<li id="' + key + '">' + val + '</li>');
         });
 
         $('#results').html(
            $('<ul/>', {
               'class': 'results-list',
               html: items.join('')
            })
         );
      }
   });
}

This function should add a list with all the items resulted from the request.

Example of use:

View Code HTML
<a href="javascript:;" onclick="execAjax('fruits')">fruits</a>
<a href="javascript:;" onclick="execAjax('vegetables')">vegetables</a>
<a href="javascript:;" onclick="execAjax('furniture')">furniture</a>
 
<div id="results"></div>

And the ajax.php return an array encoded in json.

$results = array(
   'fruits' => array(
      'apple',
      'bannana',
      'orange'
   ),
   'vegetables' => array(
      'potato',
      'carrot',
      'onion'
   ),
   'furniture' => array(
      'chair',
      'desk'
   )
);
 
$type = $_GET['type'];
 
echo json_encode($results[$type]);

If we’ve clicked on the “fruits” link, will get a result like:

View Code JSON
["apple","bannana","orange"]

This encoded array will be transformed in list with the “each” function from jquery and the result that you should see is:

View Code HTML
<div id="results">
   <ul class="results-list">
      <li id="0">apple</li>
      <li id="1">bannana</li>
      <li id="2">orange</li>
   </ul>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>