Ecommerce Developer
 
 

Code

Tutorial: Using AJAX with jQuery and PHP

 

When I was growing up, AJAX was what my mom used to clean the kitchen. But now it’s shorthand for Asynchronous JavaScript and XML, which refers to using JavaScript to make POST or GET requests to a backend process. And in this introductory-level tutorial, I’ll show you how to set-up a simple AJAX call using the jQuery JavaScript library and PHP.

XML May Not Be Included

In spite of its name, the term AJAX is often applied even when XML is not part of the equation. And for this tutorial, I am using the term in the broader sense of making POST and GET requests.

So specially, what I'm going to show you is how to use AJAX (sans XML) to make a call from a web page to a backend PHP process that will return some data that is then displayed in the web page. This is really a simple process, and in just a few minutes you’ll be making AJAX calls in your sleep.

How AJAX Improves User Experience

In the past, web users had been forced to wait for a web page to completely reload all graphics and content when something on the page changes for any reason.

For instance, say your client, which sells widgets, wants to show Twitter tweets from happy customers on its home page. To do this without AJAX, you'd have to reload the page every few minutes to check for new tweets. If the page was heavy with graphics—say a hero image or a dozen product images—the reload process force your client’s site visitors to wait for an unresponsive site. But with AJAX, you’d only need to reload the tweets, and site visitors could keep shopping undisturbed.

Getting Started

For convenience, I've written a small bit of HTML that I'll be using to illustrate the process.

     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
     <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
          <title>An Awesome jQuery Example</title>
          </head>
          <body>
          <p id="the_question">Why did the chicken cross the road?</p>
          <p id="the_answer"></p>
          <input type="button" id="the_button" value="Click here to find out. It's hilarious"/>
          </body>
      </html>

Copy and paste this code into your favorite editor, save it, and upload to your web server. It should look something like this:

<span class='full_width'>![](/uploads/images/0000/4789/ecd-ajax-php-tut1.jpg)</span> 

I'm dying to know why the fowl did it. But for now, when I click the button nothing happens. What a letdown. Let's do something about that.

Step 1: Get jQuery

The jQuery JavaScript library can be downloaded at jQuery.com. Once downloaded and neatly tucked away in your file structure, jQuery is inserted into the HTML just like any other JavaScript file. For best practices, we'll put the jQuery just before the closing </body> tag, so that the end of our HTML page now looks like this:

        <script type="text/javascript" src="/path_to_your_javascript/jquery-1.3.2.min.js"></script>
    </body>
</html>

Step 2: Assign the Event Handler

Now that jQuery is installed, it's time to do something with it. First, we want to make that button do something when you click it. Some might suggest using inline JavaScript to assign an "onclick" event to the button like so:

     <input type="button" id="the_button" onclick="alert('Sean Rowe is Awesome');" value="Click me"/>

But inline JavaScript can be tacky (a technical web development term) and should, generally, be avoided. Rather let’s create a short function that does, in fact, assign an onclick event handler to the button, but does so in a more elegant way—again, we’re amending the HTML.

               <script type="text/javascript" src="/path_to_your_javascript/jquery-1.3.2.min.js"></script>
               <script language="JavaScript" type="text/javascript">
                    $(document).ready(function() {
                         $('#the_button').click(function() {
                    // do something here ya'll. 
                });
            });
        </script>
    </body>
</html>

So what's going on here? The code $(document).ready() is used in place of the inline "onload" event, which is typically placed inside the <body> tag. This snippet of code guarantees that the function you provide as an argument will be run after the page has completely loaded on all supported browsers. The anonymous function we're passing to the click function will be executed when the button is clicked. Notice that we are identifying the button by its ID, #the_button.

Step 3: Make the AJAX Call

We want the button to fill in the "the_answer" <p> element with the answer to what happens when the chicken crosses the road, which our backend PHP script will provide. Again, we’re adding to the HTML. We will use jQuery's AJAX function like so:

              <script type="text/javascript" src="/path_to_your_javascript/jquery-1.3.2.min.js"></script>
              <script language="JavaScript" type="text/javascript">
                   $(document).ready(function() {
                       $('#the_button').click(function() {
                            $.ajax({
                            type: "GET",
                            url: "chicken_answer.php",
                            data: "first=Sean&last=Rowe",
                            success: function(msg){
                            jsonObj = eval('(' + msg + ')'); // we're getting back JSON text, so we have to convert it to a JavaScript object.
                            $('#the_answer').html(jsonObj.theAnswer);
 	                        }
                            });
                       });
                   });
               </script>
          </body>
     </html>

That's it for the JavaScript portion of this tutorial. On to the PHP script, where all things chicken-and-road related will be revealed.

Step 4: The PHP script

You may have noticed that the PHP script is returning a JavaScript Object Notation (JSON) object. The idea is that the PHP script will create an array of return values, and then convert that array it into a JavaScript object by using the json_encode() method. In this case, it will be an array with only one value – why exactly did the chicken cross the road? Place the following PHP code into a file called “chicken_answer.php” and add it to the same directory where you placed the index.html created earlier:

     <?php 
          $rval = array('theAnswer' => 'To get to the other side, ' . $_REQUEST['First'] . ' ' .$_REQUEST['Last']); echo json_encode($rval);
     ?>

We were able to access the PHP array value for "theAnswer" by converting it to a JSON string and evaluating it in the JavaScript method. That allowed us to then set the HTML inner value of the <p> "the_answer" with the value of jsonObj.theAnswer. Notice too that the keys "First" and "Last" were available in the $_REQUEST object just as they are in typical web pages. To send something in the request, put it in comma format inside the "data" section of the AJAX call.

Now, if you refresh your page and click the button, you'll see something like this:

<span class='full_width'>![](/uploads/images/0000/4794/ecd-ajax-php-tut2.jpg)</span> 

Summing Up

I've shown you how easy it is to create an AJAX-driven web page using jQuery and PHP. By using the basics I've shown you here, you should be able to create fast-loading and cool content for your ecommerce projects.

Related Articles

0 Comments

Rss-sm