Advertisement
News

How to Make AJAX Requests With Raw JavaScript: Part 2

by

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

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",
            "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 += '
  • ' + 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.

    <?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.


    Related Posts
    • Code
      PHP
      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
      PHP
      Building a CodeIgniter Web Application From Scratch - Part 1Web app retina preview
      In this series we're going to build a web billboard application from scratch, we're going to use CodeIgniter to handle the back-end service and BackboneJS for the web client. In the first two parts of the series we'll create the back-end service and then the client application in the last two.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…