Web Programming/AJAX

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Resources:

Each web applications has at least two parts: a client side and a server side. The client side runs in the browser serving as the user interface of the web app. The server side run on a server, which allows app to implement the business logic and have access to various resources, e.g. the file system, databases, or other services. The interactions between the client side and the server side are in the form of requests and responses. Traditional a request is triggered when the user types a new URL in the address bar or click on the page. The response to the request would be a new page. Before the new page arrives the user has nothing to interactive. Such delays can be caused by network latency or server issues, which are hard to control. To offer good user experience our app should stay interactive at all times. Refreshing the whole page to respond to every request is highly inefficient because often time only a small portion of the page need to be updated.

AJAX stands for Asynchronous JavaScript and XML. It is not a new programming language, but a new way to use JavaScript to exchange data between the client side and the server side in a asynchronous fashion. AJAX is based on standards includes XMLHttpRequest object, DOM manipulation with JavaScript, and XML and JSON.

The following are a few commonly used AJAX methods in JQuery. The load() method loads data from a server and puts the returned data into the selected element. The AJAX get() and post() methods with send the requests using the respective HTTP request types.

The following example show the modified version of our TODO list example using AJAx.

<html>
<head>
  <title>Add a TODO</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    // load the todo list
    $("#list").load("list.php?delay=10");
    
    $(document).ajaxStart(function() {
      $("#loader").show();
    });
    $(document).ajaxStop(function(){
      $("#loader").hide();
    })

    $("button").click(function(){
      $.get("add_submit.php",
      { 
        todo: $('#todo').val(),
        delay: 10
      },
      function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
        $("#list").empty();
        $("#list").append(data);
      })
    });

  });

</script>
</head>
<body>
<label>TODO:<input type="text" id="todo"/></label>
<button>Add</button><br/>
<img id="loader" width="50px" heigth="50px" src="ajax_loader.gif"/>
<div id="list"></div>
</body>
</html>

Note the client side uses JavaScript code to load the todo list and send the request for adding a new item in the list. The PHP scripts being requests server as the server side by offering a web API. Each PHP script can be viewed a function, which returns data for each parameter combination. The server scripts are as follows:

<?php
/* add_submit.php */
$todo = $_REQUEST["todo"];
$delay = $_REQUEST["delay"];

if (!isset($delay)){
  $delay = 0;
}

sleep($delay);

if (strlen(trim($todo)) != 0){ 
  file_put_contents("todolist.txt", $todo."\n", FILE_APPEND);
  $lines = file("todolist.txt");
?>
<li><?=array_pop($lines)?><a href="delete.php?line_number=<?=count($lines)-1?>">[x]</li>
<?php  
}
?>
<ul>
      <?php
           /* list.php */
	    $delay = $_REQUEST['delay'];
        if (!isset($delay)){
          $delay=0;
        }
        sleep($delay);
    	$todos = file("todolist.txt", FILE_IGNORE_NEW_LINES); 
        #print_r( $todos);
        $count = count($todos);
        for ($i=0; $i<$count; $i++){
      ?>
          <li><?=$todos[$i]?>
			[<a href="delete.php?line_number=<?=$i?>">x</a>]</li>
      <?php
        }
      ?>
</ul>