Ajax form with jQuery

Building an Ajax form with jQuery requires two components:

  1. a server side script to process data
  2. the ajax() object of jQuery

Suppose that you want a search form to get some definitions of web standards. The server-side script is as follows:

<?php

header('Content-Type: text/plain');

$q = $_GET['q'];
$response = '';

if(preg_match('/^\s+$/', $q) || empty($q)) {
    $response = '<p class="error">You must provide a search term.</p>';
    echo $response;
} else {

   $term = strtoupper($q);
   $definitions = array(
                  'CSS' => 'A stylesheet language.',
    'DOM' => 'An interface to manipulate web documents.',
    'XML' => 'An extensible markup language.'
    );
   
   foreach($definitions as $definition => $value) {
   
       if($definition == $term) {
       
           $response = '<div class="success"><h2>' . $definition . '</h2><p>' . $value . '</p></div>';
    
    break;
       
       } else {
       
       
           $response = '<p class="error">No term found.</p>';
    
    break;
       
       
       }
   
   
   }
   
   
   echo $response;
   
   
    
   


}
?>

Note that we're serving our response in plain text, because it's faster. Also note that we're simply using an associative array to mimic the behavior of a database. The jQuery code is really simple:

 $(document).ready(function() {
    
    
        $('#test').submit(function() {
 
 if($('p.error').size()) {
 
     $('p.error').remove();
     
 }
 
 var query = $('#q').val();
 var data = 'q=' + query;
 $.ajax({
 
     type: 'GET',
     url: 'process.php',
     data: data,
     success: function(html) {
     
        $('<div></div>').html(html).insertAfter('#test');
     
     
     }
 
 
 });
 
 return false;
 
        });
    
    
    });

First of all, you need to clean all the previous Ajax messages inserted after a form submission. Then you build up your query string and pass it to the ajax() object, also specifying the type of your request, the URL of the server-side script and the data passed with your query (in this case, it's a GET query). If the request is successful, you insert the result into an HTML element. Be aware that you have also to prevent the default action of the form from happening: if you don't do so, your browser will open the page specified in the action attribute of your form.

If you want to test this example, try to insert some valid values such as CSS, DOM and XML and then some dummy text. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.