How to Make AJAX Requests With Raw JavaScript: Part 2

How to Make AJAX Requests With Raw JavaScript: Part 2

Jun 2nd in Screencasts by Jeffrey Way

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!

PG

Author: Jeffrey Way

Hi, I'm Jeff. I'm the editor of Nettuts+, and the Site Manager of Theme Forest. I spend too much time in front of the computer and find myself telling my fiance', "We'll go in 5 minutes!" far too often. I just can't go out to dinner while I'm still producing FireBug errors...drives me crazy. During my free time, I sporadically write articles for my own personal blog. If it will keep you in the good graces of the church, follow us on Twitter.

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

    Check out some more great tutorials and articles that you might like

    Enjoy this Post?

    Your vote will help us grow this site and provide even more awesomeness

    Plus Members

    Source Files, Bonus Tutorials and
    More for $9 a month for all TUTS+
    sites in one subscription.

    Join Now

    User Comments

    ( ADD YOURS )
    1. PG

      Napoleon June 2nd

      Ist One in !

      ( Reply )
      1. PG

        Napoleon June 2nd

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

        ( Reply )
        1. PG

          Jeffrey Way June 2nd

          Great! Thanks so much. :)

        2. PG

          d1ve2blu3 June 3rd

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

    2. PG

      Meshach June 2nd

      Thanks for the screencast I will watch it ASAP.

      ( Reply )
    3. PG

      Myfacefriends June 2nd

      many thanks jeff

      ( Reply )
    4. PG

      Moksha June 2nd

      wonderful nice to watch a new screen cast

      ( Reply )
    5. Much better now! %) Good work!

      ( Reply )
      1. PG

        Jeffrey Way June 2nd

        Definitely. Good work to you too.

        ( Reply )
    6. PG

      Morten Najbjerg June 2nd

      Great basic tutorials. More of this would be appreciated.

      ( Reply )
    7. PG

      wpninja.pl June 2nd

      Thanks :)

      ( Reply )
    8. PG

      Michael June 2nd

      Very useful. Thanks for a great tutorial.

      ( Reply )
    9. PG

      web develop June 2nd

      Great work. Thanks.

      ( Reply )
    10. PG

      9swords June 2nd

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

      ( Reply )
    11. PG

      Jan June 2nd

      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!

      ( Reply )
      1. Second variant probably will be faster.

        ( Reply )
      2. PG

        Jeremy June 3rd

        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.

        ( Reply )
      3. PG

        Mic June 3rd

        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

        ( Reply )
    12. PG

      Farhan June 3rd

      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.

      ( Reply )
    13. PG

      Phil June 3rd

      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?

      ( Reply )
    14. PG

      Andrew June 3rd

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

      ( Reply )
    15. PG

      Dario Gutierrez June 3rd

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

      ( Reply )
    16. PG

      Jeremy June 3rd

      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

      ( Reply )
    17. PG

      Mic June 3rd

      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.

      ( Reply )
    18. PG

      Diego SA June 3rd

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

      ( Reply )
    19. PG

      Mark Roberts June 3rd

      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.

      ( Reply )
      1. PG

        Jeffrey Way June 3rd

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

        Maybe something similar to that?

        ( Reply )
    20. PG

      chris June 3rd

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

      ( Reply )
      1. PG

        Jeffrey Way June 3rd

        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.

        ( Reply )
    21. PG

      Keleo June 3rd

      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!

      ( Reply )
    22. PG

      HJaber June 4th

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

      ( Reply )
    23. PG

      Sam June 19th

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

      ( Reply )
    24. PG

      Adrian June 28th

      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.

      ( Reply )
    25. PG

      Brian Temecula July 11th

      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?

      ( Reply )
    26. PG

      myName July 21st

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

      ( Reply )
    27. PG

      Gerome November 20th

      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.

      ( Reply )
    28. PG

      HJaber June 4th

      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.

      ( Reply )
    1. Arrow
      Gravatar

      Your Name
      June 4th