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.
View Code PHP
$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>
|