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

How to Make AJAX Requests With Raw JavaScript: Part 2

DiggThis

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

    Add Comment

    Discussion 37 Comments

    1. Napoleon says:

      Ist One in !

    2. Meshach says:

      Thanks for the screencast I will watch it ASAP.

    3. Moksha says:

      wonderful nice to watch a new screen cast

    4. Much better now! %) Good work!

    5. Morten Najbjerg says:

      Great basic tutorials. More of this would be appreciated.

    6. Michael says:

      Very useful. Thanks for a great tutorial.

    7. web develop says:

      Great work. Thanks.

    8. 9swords says:

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

    9. Jan says:

      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!

    10. Farhan says:

      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.

    11. Phil says:

      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?

    12. Andrew says:

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

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

    14. Jeremy says:

      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

    15. Mic says:

      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.

    16. Diego SA says:

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

    17. Mark Roberts says:

      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.

    18. chris says:

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

      • Jeffrey Way says:

        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.

    19. Keleo says:

      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!

    20. HJaber says:

      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()#

    21. Sam says:

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

    22. Adrian says:

      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.

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

    24. myName says:

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

    25. Gerome says:

      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.

    26. HJaber says:

      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.

    Add a Comment