Using Jquery to Implement Ajax

Course- Javascript >

As you probably now realize, Ajax programming from scratch can be a little cumbersome. Fortunately, jQuery solves this for you, letting you write Ajax routines in few lines of code.

There are a number of jQuery methods for performing Ajax calls to the server; the more frequently used ones are described here.

load()

When you simply want to grab a document from the server and display it in a page element, load() might be all you require. The following code snippet gets the file newContent.html and adds its content to the element with id="elem":

$(function() {
$("#elem").load("newContent.html");
});                 
                 

A neat trick is that you can pass a selector along with the URL, and only get the part of the page corresponding to that selector:

$(function() {
$("#elem").load("newContent.html #info");
});                 
                 

Here you have added a jQuery selector after the URL, separated by a space. This causes jQuery to pass back only the content of the container specified by the selector; in this case, the element with ID of info.

When load() gives you too little control, jQuery offers methods to send GET and POST requests too.

get() and post()

The two methods are similar, simply invoking different request types. You don’t need to select a jQuery object (such as a page element or set of elements); instead, you can call get() or post() directly using $.get() or $.post(). In its simplest form, the get() or post() method takes a single argument, the target URL.

You’ll often want to send data to the server using get() or post(). Such data is sent as a set of parameter and value pairs in an encoded string.

If you are collecting data from form fields, jQuery offers the handy serialize() method that can assemble the form data for you: var formdata = $('#form1').serialize();

In most cases, though, you’ll want to do something with the returned data. To do that, you pass a callback function as an argument:

$.get("serverScript.php",
{param1: "value1", param2: "value2"},
function(data) {
alert("Server responded: " + data);
});                 
                 

The syntax for post() is essentially the sandye:

$.post("serverScript.php",
{param1: "value1", param2: "value2"},
function(data) {
alert("Server responded: " + data);
});                 
                 

ajax()

For the ultimate flexibility, the ajax() method allows you to set virtually every aspect of the Ajax call and how to handle the response. For full details of using ajax() see the documentation at http://api.jquery.com/jQuery.ajax/.

Try it Yourself: An Ajax Form with jQuery

Let’s round off this section with an example of a simple Ajax form submission powered by jQuery.

We’ll work with this simple HTML form:

<form id="form1">
Name<input type="text" name="name" id="name"><br />
Email<input type="text" name="email" id="email"><br />
<input type="submit" name="submit" id="submit" value="Submit
Form">
</form>                 
                 

You’re going to use jQuery to carry out the following tasks:

  • Check that both input fields contain text.
  • Submit the form via Ajax using HTTP POST.
  • Print the data returned from the server into a <div> element on the page. To check that both fields have had data entered, you use a simple function:
function checkFields(){
return ($("#name").val() && $("#email").val());
}                 
                 

For the function to return Boolean true, the value attribute of both form fields must contain some text data; if either field is empty, the blank field will be interpreted as “falsy” and the logical AND (&&) operator will cause false to be returned from the function.

Next, apply jQuery’s submit() event handler to detect form submission. If your function checkFields() returns false, the default behavior will be canceled and the form won’t be submitted; otherwise, jQuery serializes the data and sends a post() request to the server script.

The jQuery serialize() method is used to collect the form information into a serialized string to send as a data payload with the Ajax call.

For this example, the server script test.php doesn’t do anything except format the information it receives and send it back as a little piece of HTML:

<?php
echo "Name: " . $_REQUEST['name'] . "<br />Email: " .
$_REQUEST['email'];
?>                 
                 

Finally, the callback function displays the returned information on the page:

function(data){
$("#div1").html(data);
}                 
                 

The code shown like this.

<!DOCTYPE html>
<html>
<head>
<title>Ajax Form Submission</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
function checkFields(){
return ($("#name").val() && $("#email").val());
}
$("#form1").submit(function(){
if(checkFields()){
$.post(
'test.php', $("#form1").serialize(),
function(data){
$("#div1").html(data);
}
);
}
else alert("Please fill in name and email fields!");
return false;
});
});
</script>
</head>
<body>
<form id="form1">
Name<input type="text" name="name" id="name"><br />
Email<input type="text" name="email" id="email"><br />
<input type="submit" name="submit" id="submit" value="Submit
Form">
</form>
<div id="div1"></div>
</body>
</html>                 
                 

To run this example you need to upload both the file above code and the server file test.php to a web server with PHP support.

Trying to submit the form with one or both of the input fields left blank will cause the script to issue an alert message and prevent the form submission.

A successful form submission should result in the formatted data being presented on the page, as shown in snapshot. The figure also shows Firebug Lite displaying details of the Ajax call and response.

an ajax form using jquery