Mar 9, 2012

AJAX with JQuery and PHP

AJAX stands for Asynchronous JavaScript And XML, and allows us to make our websites seem more dynamic.

A first example...

Our first example outlines how this is done within a single page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <title>Ajax With Jquery</title>

       <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our own JQuery code to do the AJAX-y stuff -->
       <script type="text/javascript" charset="utf-8">

          $(document).ready(function(){
             $('#txtValue').keyup(function(){
                 $('#display').html($(this).val());
             });
          });

       </script>
    </head>

    <body>
       <label for="txtValue">Enter a value : </label>
       <input type="text" name="txtValue" value="" id="txtValue">

        <div id="display"></div>
    </body>
</html>



Pretty much all this will do is update the display section of of the page with the latest text in the text box. The event the script will listen for is a 'Key Up' event on the txtValue item. Pretty simple really...

Something a little more AJAX - The HTML

So our original example just showed how we could manipulate the DOM (Document Object Model) of the browser during run-time, without a page refresh. How can we use this knowledge utilizing the power of PHP? Well, first let us edit our HTML to something we can manipulate:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

       <title>Ajax With Jquery</title> <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our external JS script file... we will write this up later -->
       <script src="tutorial.js"></script>
    </head>

    <body>
         <form name="contact" method="post" action="">
            <label for="txtValue">Enter a value : </label>
            <input type="text" name="txtValue" value="" id="txtValue">
            <input type="button" name="submit" class="button" id="submit_btn" value="Send" />
         </form>
         <div id="display">
         </div>
   </body>
</html>

The JavaScript and JQuery file

Now we need to create the JavaScript file:

$(function() {
    // This will run when the item of class 'button' is clicked
    $(".button").click(function() {
 
         // Grabs the text input
         var name = $("input#txtValue").val();
         var dataString = 'txtValue='+ name;
         // This creates the AJAX connection
         $.ajax({
            type: "POST",
            url: "tutorial.php",
            data: dataString,
            dataType: 'json',
            success: function(data) {
               $('#display').html(data.text);
            }
         });
         return false;
    });
});

This simply sends data to an external php script (tutorial.php) and then change the contents of <div id="display"> to whatever it returns. This is much more AJAX-y.

The PHP file

The final thing we have to do is write the PHP output...

<?php
if (isset($_POST['txtValue'])) {
    $txtValue = stripslashes(strip_tags($_POST['txtValue']));
} else {$txtValue = 'Nothing';}
    echo json_encode(array('text' => $txtValue));
?>


Of course, there are multiple ways of achieving the same result, but this should help you get started.

Reference

1 comment:

  1. Very helpful :)

    There is one typo in the tutorial.php file though.

    It should be:
    $txtValue = stripslashes(strip_tags($_POST['txtValue']));

    ReplyDelete

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!