How to Make AJAX Requests With Raw JavaScript: Part 2
videos

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!

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.


    Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
    • Napoleon

      Ist One in !

      • Napoleon

        Hey Jeff thanks for the Netbeans Twilight Theme I just finished converting it to Geany and its great!

        • http://www.jeff-way.com Jeffrey Way
          Author

          Great! Thanks so much. :)

        • d1ve2blu3

          hey, Napoleon. how to create theme for geany??

    • Meshach

      Thanks for the screencast I will watch it ASAP.

    • http://myfacefriends.com Myfacefriends

      many thanks jeff

    • http://mokshasolutions.com Moksha

      wonderful nice to watch a new screen cast

    • http://nvartolomei.com/ Nicolae Vartolomei

      Much better now! %) Good work!

      • http://www.jeff-way.com Jeffrey Way
        Author

        Definitely. Good work to you too.

    • Morten Najbjerg

      Great basic tutorials. More of this would be appreciated.

    • http://wpninja.pl wpninja.pl

      Thanks :)

    • http://www.michaelbubbo.com/blog Michael

      Very useful. Thanks for a great tutorial.

    • http://www.devirtuoso.com web develop

      Great work. Thanks.

    • http://twitter.com/9swords 9swords

      Don’t have time right now, but i am going to watch all of these.
      Thank you very much Nettuts + Jeffrey Way

    • Jan

      Can anyone tell me what is the best way to render the data from DB? What is the best practice?

      1) Using PHP to create all the DOM elements first and then just pass them to Javascript using innerHTML ?

      2) Assemble whole DOM elements using Javascript with just raw data from DB ?

      Which is the beast way or what are the differences? I’m more familiar with PHP so I create all the elements using PHP code and then just pas them via JS

      Thank you!

      • http://nvartolomei.com/ Nicolae Vartolomei

        Second variant probably will be faster.

      • http://www.wdonline.com Jeremy

        It depends on how many changes to the DOM you’re making. For small DOM changes, either way is fine. For large DOM changes, innerHTML is faster than creating the same structure with DOM methods.

      • http://beebole.com/blog Mic

        Another option you can consider is to use JS library to render your HTML on the browser. You can have a look at PURE http://beebole.com/pure

    • Farhan

      Great tut, and am looking forward to part 3! Would love to see you create a simple app with all this in the next one.

    • Phil

      Another great tutorial, thanks.

      I’ve not had any experience with JSON so this has been inspirational.

      Do you think building the response in XML would be easier to process on the client side rather than using JSON and the parser script?

    • Andrew

      Thanks so much for these tutorials! I really learn a lot!

    • http://labs.dariux.com Dario Gutierrez

      Excellent second part. This is a great reference to me because I don’t have any experience with JSON. Thanks.

    • http://www.wdonline.com Jeremy

      I have the same criticism as the first part of the series. The versions array in its current form always uses Microsoft’s first version of XmlHttp. Reversing the elements allows the latest version installed on the user’s computer to be used.

      You could also take it one step further and only check for versions 3 and 6, as per Microsoft’s XML team:

      http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx

    • http://beebole.com/blog Mic

      Don’t you think that a JSONP call would be simpler?

      Security is not an issue as you call the same domain and as you have the hand on the server you can wrap the response in a JS callback function.

    • http://www.dsaportfolio.com.br Diego SA

      Unfortunately I didn’t see the 1st part…. yet. I’ll check both, thanks!

    • Mark Roberts

      Jeff thanks for great clear tut, on a slight aside I wonder if anyone can help a designer struggling with a bit of jquery syntax, basically I want jquery to look for value in a submitted input field and if that value is equal to a specified value then do something, elsee do nothing. Any advice greatly appreciated.

      • http://www.jeff-way.com Jeffrey Way
        Author

        var value = $(‘input:submit’).val();
        if(value === ‘some string’) {
        console.log(‘wahoo’);
        }

        Maybe something similar to that?

    • chris

      I heard you say in this movie, or in part 1: jquery will not be there for ever, what do you mean with that?

      • http://www.jeff-way.com Jeffrey Way
        Author

        I mean that technologies will come and go. Prototype was a the huge JS framework years ago. That’s obviously not the case anymore. That’s all I meant.

    • http://keleo.tel/ Keleo

      IMO, its still way better to rely on jQuery instead of the raw javascript stuff. You can be sure that the .ajax() call works and use its result, instead of strugling around with code you do not need to know.
      Isn’t that what a framework is originally made for? To keep you away from implementation questions…
      Well, beside that, thanks for the tut!

    • http://www.OEMsTrade.com HJaber

      I just wanted to post an emails.cfm and index.cfm for those who are interested in a Coldfusion version. You will have to create a db with the same fields as in Jeff’s tutorial in order for this to work.

      index.cfm

      INSERT INTO contactInfo (name,email)
      VALUES (,)

      Add New

      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.cfm’, function(xhr) {
      var response = JSON.parse(xhr.responseText);
      var container = document.getElementById(‘container’);

      var vals = response.DATA;
      var cols = response.COLUMNS;

      var colMap = new Object();

      for(var i = 0, len = cols.length; i < len; i++){
      colMap[cols[i]] = i;
      }

      for(var i = 0, len = vals.length; i < len; i++){
      container.innerHTML += ‘‘ + vals[i][colMap["NAME"]] + ‘ : ‘ + vals[i][colMap["EMAIL"]] + ”;
      }

      });

      emails.cfm

      SELECT * FROM contactInfo

      #getEmails()#

    • Sam

      Thanks for showing the innards! I really enjoyed both of the videos, clear and precise instruction.
      <- new fan

    • Adrian

      A suggestion for this video:
      in the PHP script, have the “Content-Type” header be “text/javascript”, like “header(‘Content-Type: text/javascript’);”

      A suggestion for the next video:
      How to use XML for the data instead if JSON.

    • http://www.brianswebdesign.com Brian Temecula

      I’ve never used JSON before, but it does seem pretty handy for returning data from the database. If there was a double quote in the data, would the json_encode function automatically escape it? I’m also wondering if there is a better way to return data. Text, CSV, XML could be used, but in the end I guess it comes down to what is parsing on the client side. Is JSON fastest/best?

    • myName

      What about: $result = “[ " . implode( ",", $construct ) . " ]“; ? Thats easier than the if(…) echo “,” …

    • Gerome

      Hi,

      Would anyone be able to help, I want to turn Jeffrey’s example into a multi-page form. I need to build a survey with various question and answer pages.

      My method would be to pass the Last ID created by the insert statement on the first (start) page into a session variable in the second page and then use that session variable to update (via an update stmt statement) that particular id’s record fields.

      I have managed to create the stmt statement for the insert however, I am having trouble creating a stmt statement for the update query, which references the id stored in the session variable.

      Would anyone be able to help please.

    • kevin

      how did u get the toolbars (disable, cookies, forms, images.. ) in your firefox browser?

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Kevin – it’s called the web developer toolbar, by Chris Pederick.

    • http://www.OEMsTrade.com HJaber

      I should have commented the code, but I wanted to explain something regarding the 2 for loops at the end of the script. Coldfusion returns DATA and COLUMNS and does not return the JSON in the format the script expected. I seen an example a long time ago on Ray Camden’s website where he showed how to convert the Query into a JSON string for Javascript. I thought it was a good technique and went with it for my example.