Welcome to the seventh part of a series introducing the jQuery JavaScript library. Made up of eight comprehensive articles, this series provides you with the right pointers to get started using this JavaScript software so you can take advantage of its remarkable functionality.
Ajax and the JQuery JavaScript Library - Sending GET and POST requests with Ajax (Page 3 of 4 )
If you found it easy to work with the “$.get()” and “$.post()” methods reviewed in the prior segment, then you'll probably find it even easier to utilize one called “$.ajax().”
In simple terms, this method is a combination of the other two. It permits you to trigger GET and POST HTTP requests with Ajax in a truly intuitive manner. However, I’m sure that you’ll understand much more easily how this method works if you have a look at the following code sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<h1>Basic example on using jQuery with $.ajax() method</h1>
</body>
</html>
(definition of "savedata.php” file)
<?php
$data=$_POST['fname'].' '.$_POST['lname'];
$fp=fopen('data.txt','w');
fwrite($fp,$data);
fclose($fp);
echo $data;
?>
As shown above, it’s extremely simple to create an Ajax application through the “$.ajax()” method. In this case, the sample application behaves nearly identically to the ones developed in the previous section; that is, first it triggers a POST request and passes my first and last names to the web server, which will be saved to a “data.txt” file.
Once this operation has been completed successfully, the data is sent back to the client and displayed via an alert box. Logically, it’s clear to see here that the “ajax()” method gives you more control over how the corresponding HTTP must be handled. However, it’s perfectly valid to use “$.get()” and “$.post()” if you feel more comfortable working with them.
So far, so good. At this stage, you hopefully learned how to build some basic Ajax applications by using the jQuery library. Of course, in this tutorial I’m only providing you with an introductory guide to using the “$.get(),” “$.post()” and “$.ajax()” methods explained earlier. But if you need to develop a full-blown Ajax program using these methods, the process will require much more practice.
And now that I mentioned “practice,” it’s very probable that you may want to try out the animation module that comes with jQuery. It allows you to create appealing visual effects with minor efforts.
Therefore, in the final section of this tutorial I’m going to teach you how to use two handy methods, called “show()” and “hide()” respectively, which will come in useful for displaying and hiding a selected web page element.
To learn more on how to employ these methods in a useful way, please read the following section.