A few weeks ago, I demonstrated how to make AJAX requests with raw JavaScript. In today's screencast, we'll take things a step further as we use PHP to query a database, convert it to the JSON format, and use Javascript to asynchronously request this information and display it on the page. If you're just getting started with these sorts of concepts, this is the perfect video for you!
Video

Final "Load" Script
This block of code asynchronously requests a page, and then uses Douglass Crockford's "Parse" script to create a new global object. That way, we can easily filter through the returned JSON data.
function load(url, callback) { var xhr; if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest(); else { var versions = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"]; for(var i = 0, len = versions.length; i < len; i++) { try { xhr = new ActiveXObject(versions[i]); break; } catch(e){} } // end for } xhr.onreadystatechange = function() { if((xhr.readyState < 4) || xhr.status !== 200) return; callback(xhr); }; xhr.open('GET', url, true); xhr.send(''); } load('emails.php', function(xhr) { var response = JSON.parse(xhr.responseText); var container = document.getElementById('container'); for(var i = 0, len = response.length; i < len; i++) { container.innerHTML += '<li><strong>' + response[i].name + '</strong> : ' + response[i].email + '</li>'; } });
Final PHP
Slightly modified from the video to improve efficiency -- a much more elegant solution than what I originally came up with on the spot.
<?php /* Step 1: query the database Step 2: Cycle through the returned data and convert it to the JSON format. Step 3: Echo returned data -- to be retrieved with Javascript */ $mysql = new mysqli('localhost','root','root','ajaxTut') or die('There was a problem'); if($result = $mysql->query('SELECT * FROM contactInfo')) { $returnedArray = array(); while($row = $result->fetch_object()) { $returnedArray[] = $row; } echo json_encode($returnedArray); } else { // error occurred echo 'error: ' . $mysql->error; }
I hope you all are enjoying this "video series that was never meant to be." Originally, it was planned as a single tutorial; however, due to the fact that there is SO much to cover, I'd like to continue creating more videos for you -- that is, if you'll have them. Feel free to let me know what you'd like to learn next.
- Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post