In this article we will be talking about the basic usage of Ajax with jQuery 1.4.2 production (24KB, Minified and Gzipped).
In order to use the JavaScript examples in this article, you should first download jQuery and include it on your page using:
Throughout this article our Ajax scripts will communicate with ‘serverscript.php‘ our Server script.
- <script type="text/javascript" src="jquery-1.4.2.js"></script>
Method One - POST (Asynchronous with data):
- <?php
- if(isset($_POST['firstname']) &&
- isset($_POST['lastname'])) {
- echo "Hey {$_POST['firstname']} {$_POST['lastname']},
- you rock!\n(repsonse to your POST request)";
- }
- if(isset($_GET['firstname']) &&
- isset($_GET['lastname'])) {
- echo "Hey {$_GET['firstname']} {$_GET['lastname']},
- you rock!\(response to your GET request)";
- }
- ?>
Transfer data to the server (using POST method), and retrieve a response:
Method Two - GET (Asynchronous with data):
- function doAjaxPost() {
- $.ajax({
- type: "POST",
- url: "serverscript.php",
- data: "firstname=clint&lastname=eastwood",
- success: function(resp){
- // we have the response
- alert("Server said:\n '" + resp + "'");
- },
- error: function(e){
- alert('Error: ' + e);
- }
- });
- }
- doAjaxPost();
Transfer data to the server (using GET method), and retreive a response:
Note that GET is the default type for Ajax calls using jQuery, so we really do not need to explicitly state it, but I’ve placed it there just for clarity.
- function doAjaxGet() {
- $.ajax({
- type: "GET",
- url: "serverscript.php",
- data: "firstname=clint&lastname=eastwood",
- success: function(resp){
- // we have the response
- alert("Server said:\n '" + resp + "'");
- },
- error: function(e){
- alert('Error: ' + e);
- }
- });
- }
- doAjaxGet();
Practical jQuery Example using POST:
Well there you have it, not too tricky and with a weight of only 24Kb for the base library you can’t go wrong. Of course, jQuery can be used for a whole heap of other tasks.
- <html>
- <head>
- <script type="text/javascript" src="jquery-1.4.2.js"></script>
- </head>
- <body>
- <script>
- function doAjaxPost() {
- // get the form values
- var field_a = $('#field_a').val();
- var field_b = $('#field_b').val();
- $.ajax({
- type: "POST",
- url: "serverscript.php",
- data: "firstname="+field_a+"&lastname="+field_b,
- success: function(resp){
- // we have the response
- alert("Server said:\n '" + resp + "'");
- },
- error: function(e){
- alert('Error: ' + e);
- }
- });
- }
- </script>
- First Name:
- <input type="text" id="field_a" value="Sergio">
- Last Name:
- <input type="text" id="field_b" value="Leone">
- <input type="button" value="Ajax Request" onClick="doAjaxPost()">
- </body>
- </html>
Until next time (when we cover MooTools), Happy A’jaxing!
0 comments
Post a Comment