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:
- <script type="text/javascript" src="jquery-1.4.2.js"></script>
Throughout this article our Ajax scripts will communicate with ‘serverscript.php‘ our Server script.
- <?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)";
- }
- ?>
Method One – POST (Asynchronous with data):
Transfer data to the server (using POST method), and retrieve a response:
- 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();
Method Two – GET (Asynchronous with data):
Transfer data to the server (using GET method), and retreive a response:
- 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();
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.
Practical jQuery Example using POST:
- <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>
0 comments:
Post a Comment