How to Make AJAX Requests With Raw JavaScript: Part 2

Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

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!


After a bit of discussion on Twitter, I updated some of the PHP from this video.
You can view the revisions below.

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",

        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
        } // end for

    xhr.onreadystatechange = function() {
        if((xhr.readyState < 4) || xhr.status !== 200) return;
    };'GET', url, true);


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.

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.