How to Make AJAX Requests With Raw JavaScript: Part 2


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 += '
  • ' + response[i].name + ' : ' + response[i].email + '
  • '; } });

    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.

    Related Posts
    • Code
      Building a Customer Management App Using AngularJS and LaravelLaravel 4 auth retina preview
      When creating a single-page app we should use some kind of framework to do some of the job for us, so we can focus on the actual functionality. AngularJS fits here perfectly, because features like dynamic dependency injection and bi-directional data binding are just great. Sometimes we also require some kind of server. If you've chosen PHP then Laravel may be your best option, as it's easy to work with and pretty powerful.Read More…
    • Code
      JavaScript & AJAX
      Getting Into Ember.js: Part 5Getting into ember
      Editor's Note: The Ember.js team has shifted to an expedited release schedule and as of this publication date are on version 1.2.0. This tutorial was written pre-v1.0 but many of the concepts are still applicable. We do our best to commission timely content and these situations happen from time-to-time. We'll work to update this in the future. In part 3 of my Ember series, I showed you how you can interact with data using Ember's Ember.Object main base class to create objects that define the methods and properties that act as a wrapper for your data. Here's an example:Read More…
    • Code
      JavaScript & AJAX
      Introduction to Sails.jsSails preview 400 2
      Sails is a Javascript framework designed to resemble the MVC architecture from frameworks like Ruby on Rails. It makes the process of building Node.js apps easier, especially APIs, single page apps and realtime features, like chat.Read More…
    • Code
      Titanium Mobile
      Creating Titanium Mobile Modules Using CommonJSCommon js
      In this article we'll be discussing how to create your own mobile modules for Appcelerator's Titanium using just JavaScript and a bit of CommonJS knowledge.Read More…
    • Code
      JavaScript & AJAX
      jQuery Succinctly: jQuery and AjaxJquery cover
      The jQuery ajax() Function is the Lowest-Level Abstraction The jQuery ajax() function is the lowest level of abstraction available for XMLHttpRequests (aka AJAX). All the other jQuery AJAX functions, such as load(), leverage the ajax() function. Using the ajax() function provides the greatest functionality available for XMLHttpRequests. jQuery also provides other higher-level abstractions for doing very specific types of XMLHttpRequests. These functions are essentially shortcuts for the ajax() method.Read More…
    • Code
      JavaScript & AJAX
      Event-Based Programming: What Async Has Over SyncRefresh icon
      One of JavaScript's strengths is how it handles asynchronous (async for short) code. Rather than blocking the thread, async code gets pushed to an event queue that fires after all other code executes. It can, however, be difficult for beginners to follow async code. I'll help clear up any confusion you might have in this article.Read More…