Ajax Tutorial: Ajax Help and Tutorials: Archive For Ajax-Basics
Ajax Tutorial: Ajax Help and Tutorials: Archive For Ajax-Basics
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:
view plainprint?
1. <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.
view plainprint?
1. <?php
2. if(isset($_POST['firstname']) &&
3. isset($_POST['lastname'])) {
4. echo "Hey {$_POST['firstname']} {$_POST['lastname']},
5. you rock!\n(repsonse to your POST request)";
6. }
7. if(isset($_GET['firstname']) &&
8. isset($_GET['lastname'])) {
9. echo "Hey {$_GET['firstname']} {$_GET['lastname']},
10. you rock!\(response to your GET request)";
11. }
12. ?>
<?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:
view plainprint?
1. function doAjaxPost() {
2. $.ajax({
3. type: "POST",
4. url: "serverscript.php",
5. data: "firstname=clint&lastname=eastwood",
6. success: function(resp){
7. // we have the response
8. alert("Server said:\n '" + resp + "'");
9. },
10. error: function(e){
11. alert('Error: ' + e);
12. }
13. });
14. }
15.
16. doAjaxPost();
function doAjaxPost() {
$.ajax({
type: "POST",
url: "serverscript.php",
data: "firstname=clint&lastname=eastw ood",
success: function(resp){
// w e have the response
alert("Server said:\n '" + resp + "'");
},
error: function(e){
Transfer data to the server (using GET method), and retreive a response:
view plainprint?
1. function doAjaxGet() {
2. $.ajax({
3. type: "GET",
4. url: "serverscript.php",
5. data: "firstname=clint&lastname=eastwood",
6. success: function(resp){
7. // we have the response
8. alert("Server said:\n '" + resp + "'");
9. },
10. error: function(e){
11. alert('Error: ' + e);
12. }
13. });
14. }
15.
16. doAjaxGet();
function doAjaxGet() {
$.ajax({
type: "GET",
url: "serverscript.php",
data: "firstname=clint&lastname=eastw ood",
success: function(resp){
// w e have the response
alert("Server said:\n '" + resp + "'");
},
error: function(e){
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.
view plainprint?
1. <html>
2. <head>
3.
4. <script type="text/javascript" src="jquery-1.4.2.js"></script>
5. </head>
6. <body>
7. <script>
8. function doAjaxPost() {
9. // get the form values
10. var field_a = $('#field_a').val();
11. var field_b = $('#field_b').val();
12.
13. $.ajax({
14. type: "POST",
15. url: "serverscript.php",
16. data: "firstname="+field_a+"&lastname="+field_b,
17. success: function(resp){
18. // we have the response
19. alert("Server said:\n '" + resp + "'");
20. },
21. error: function(e){
22. alert('Error: ' + e);
23. }
24. });
25. }
26. </script>
27.
28. First Name:
29. <input type="text" id="field_a" value="Sergio">
30. Last Name:
31. <input type="text" id="field_b" value="Leone">
32. <input type="button" value="Ajax Request" onClick="doAjaxPost()">
33.
34. </body>
35. </html>
<html>
<head>
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.
Permalink Comments
Basic Ajax usage with X
March 3, 2010 at 8:45 pm · Filed under ajax-basics, ajax-news, javascript
Over the next several articles I’ll be covering the “Basic Ajax usage with X”, for example “Basic
Ajax usage with jQuery”.
The idea is to take the latest stable version of the chosen JavaScript Framework (for example
jQuery) and examine what’s required to achieve the most basic Ajax calls.
I’ll be looking at a few things here, notably the ease of use and the minimum required footprint
(in regards to download size).
Note that I will not necessary by using Ajax in the traditional sense of the word (i.e. with XML)
as the intention of these articles is to strip everything back to the absolute basics.
I’m not 100% certain about all the frameworks I’ll cover now, but I will most certainly be
covering jQuery, MooTools, Prototype, dojo, YUI and ExtJS. If I have the time, I may look at
some of the newer ones as well.
This post is a living post (I’ll revisit and link up the articles).
Cheers guys!
This example is probably the simplest example you will ever find.
We are going to use the prototype feature ‘ajax.Updater’ (see part one for more details on
prototype).
ajax.Updater allows you to specify an element ID and script URL - and whatever the script URL
prints will appear in your element ID. Simple as that.
The example below simply returns the Server time each time the button is clicked.
I’m not going to explain this bit by bit as it is just so easy to grasp.
Remember, you will need the prototype library in order to use this!
Here is the HTML/JavaScript code:
view plainprint?
1. <html>
2. <head>
3. <script src="dist/prototype.js" type="text/javascript"></script>
4. <script type="text/javascript">
5. function ajaxUpdater(id,url) {
6. new Ajax.Updater(id,url,{asynchronous:true});
7. }
8. </script>
9.
10. </head>
11. <body>
12. <div id="updateme"></div>
13. <input type="button" value="Update" onClick="ajaxUpdater('updateme','u
pdateme.php')">
14. </body>
15. </html>
<html>
<head>
<script src="dist/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function ajaxUpdater(id,url) {
new Ajax.Updater(id,url,{asynchronous:true});
}
</script>
</head>
updateme.php
view plainprint?
1. echo "Server time is: ".date("Y-m-d H:i:s");
This is part of one of many such tutorials covering Ajax with Prototype.
If you do not want to get your hand to dirty with custom Ajax code, then using the extremely
handy toolkit from prototype may be perfect.
Prototype is a very well written JavaScript framework/toolkit and come with an Ajax class to
make things nice and easy.
In this simple example I’ll show you just how easy Ajax calls are. But you will need to have your
own copy of prototype (its free!).
On a side note… if you like fancy JavaScript effects, you can extend prototype with another
library called script.aculo.us - I promise, with these you will have endless hours of fun!!
view plainprint?
1. <script src="dist/prototype.js" type="text/javascript"></script>
view plainprint?
1. <script type="text/javascript">
2. /* ajax.Request */
3. function ajaxRequest(url,data) {
4. var aj = new Ajax.Request(
5. url, {
6. method:'get',
7. parameters: data,
8. onComplete: getResponse
9. }
10. );
11. }
12. /* ajax.Response */
13. function getResponse(oReq) {
14. $('result').innerHTML = oReq.responseText;
15. }
16. </script>
<script type="text/javascript">
/* ajax.Request */
function ajaxRequest(url,data) {
var aj = new Ajax.Request(
url, {
method:'get',
parameters: data,
onComplete: getResponse
}
);
In the getResponse function above, noticed the function call $(’result’) - this is a feature of
prototype which basically replaces ‘document.getElementByID(’result’)’.
Yes, that is all we need in terms of JavaScript. I told you it was simple!!
view plainprint?
1. <input type="text" id="myval" size="10">
2.
3. <input type="button" value="GO" onClick="ajaxRequest('parse.php', 'val='
+$F('myval'))">
4.
5. <div id="result"></div>
<input type="text" id="myval" size="10">
<div id="result"></div>
Nothing fancy with the above. In order to call our JavaScript functions, we are using the
‘onClick’ event of the button.
We are passing in two values here; first the server-side script file ‘parse.php’ and the value we
want to send.
We must pass in the paramater name and value (for example: ‘val=myvalue’, just like any
querystring!), the parameter name in the case is ‘val’ and the value is the text in our text field.
We refer to this value using another prototype function $F() which is really just
‘document.getElementById(’myval’).value’.
On the server-side, our PHP script takes the value we passed $_GET['val'] and prints it back to
us as ‘You entered: yourvalue’ (where ‘yourvalue’ is what your entered in the text field!).
parse.php
view plainprint?
1. if(isset($_GET['val'])) {
2. echo "You entered: ".$_GET['val'];
3. }
if(isset($_GET['val'])) {
echo "You entered: ".$_GET['val'];
}
This is a very simple example of using just one of prototypes Ajax features, there are many more
to explorer which I will cover soon.
Have fun!
In this tutorial I’ll show you a simple method to pass any HTML form through AJAX without
the need to hard code all form fields into the JavaScript or Server Side Script. Using this simple
piece of JavaScript you can reuse it as is with any form, saving a lot of time. I’ve even added
basic validation to certain form element types (which would be expected).
view plainprint?
1. var req = createXMLHttpRequest();
2.
3. function createXMLHttpRequest() {
4. var ua;
5. if(window.XMLHttpRequest) {
6. try {
7. ua = new XMLHttpRequest();
8. } catch(e) {
9. ua = false;
10. }
11. } else if(window.ActiveXObject) {
12. try {
13. ua = new ActiveXObject("Microsoft.XMLHTTP");
14. } catch(e) {
15. ua = false;
16. }
17. }
18. return ua;
19. }
20.
21. function sendRequest(frm, file) {
22. var rnd982g = Math.random();
23. var str = "";
24. if(str = getForm(frm)) {
25. req.open('GET', file+'?'+str+'&rnd982g='+rnd982g);
26. req.onreadystatechange = handleResponse;
27. req.send(null);
28. }
29. return false;
30. }
31.
32. function handleResponse() {
33. if(req.readyState == 4){
34. var response = req.responseText;
35. document.getElementById("results").innerHTML = response;
36. }
37. }
38.
39. function getForm(fobj) {
40. var str = "";
41. var ft = "";
42. var fv = "";
43. var fn = "";
44. var els = "";
45. for(var i = 0;i < fobj.elements.length;i++) {
46. els = fobj.elements[i];
47. ft = els.title;
48. fv = els.value;
49. fn = els.name;
50. switch(els.type) {
51. case "text":
52. case "hidden":
53. case "password":
54. case "textarea":
55. // is it a required field?
56. if(encodeURI(ft) == "required" && encodeURI(fv).length < 1) {
57. alert('\''+fn+'\' is a required field, please complete.');
58. els.focus();
59. return false;
60. }
61. str += fn + "=" + encodeURI(fv) + "&";
62. break;
63.
64. case "checkbox":
65. case "radio":
66. if(els.checked) str += fn + "=" + encodeURI(fv) + "&";
67. break;
68.
69. case "select-one":
70. str += fn + "=" +
71. els.options[els.selectedIndex].value + "&";
72. break;
73. } // switch
74. } // for
75. str = str.substr(0,(str.length - 1));
76. return str;
77. }
function createXMLHttpRequest() {
var ua;
if(w indow .XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
The JavaScript code above is split into 4 functions, here is an overview of what each function
does.
createXMLHttpRequest() - This is the function which will establish the AJAX connection object,
this is called as soon as the JS file is loaded.
sendRequest() - This function is the one which is called when the form is submitted. This
function requires (passed in) the ‘Form Object’ and the ‘File Name’ of the script which will
receive the form data. When this function has been called, it takes the form object and passes it
to the JS function getForm() which in turn parses the whole form extracting all the data.
sendRequest() then takes the open AJAX connection and passes all the data to the PHP file form
processing. Finally when the request from the PHP server script is returned, it writes out the
reply to an element on the screen with the div ID ‘results’.
getForm() - This is the magic, this function reads through the whole form and extracts the field
data before returning it back to sendRequest(). It handles radio, text, password, textarea, select
and checkbox field types. It even looks for validation requests on text, password and textarea
fields (which is enabled by using title=”required” in the form element).
Simple :)
Next is a very simple form with a mixture of field types and validation requests (nothing fancy
here). Also included at the bottom is the div which prints out the results to the browser.
view plainprint?
1. <form>
2. Option One:
3. <input name="radiobutton" type="radio" value="opt1">
4. Option Two:
5. <input name="radiobutton" type="radio" value="opt2">
6. Option Three:
7. <input name="radiobutton" type="radio" value="opt3">
8. Text One*:
9. <input type="text" name="textOne" title="required">
10. Text Two:
11. <input type="text" name="textTwo">
12.
13. <select name="mySelect">
14. <option value="selectedOne">Select One</option>
15. <option value="selectedOne">Select One</option>
16. </select>
17.
18.
19. <input type="button" value=" go " onClick="sendRequest(this.form, 'pro
cess.php')">
20. </form>
21. <div id="results" />
<form>
Option One:
<input name="radiobutton" type="radio" value="opt1">
Option Tw o:
<input name="radiobutton" type="radio" value="opt2">
Option Three:
<input name="radiobutton" type="radio" value="opt3">
Text One*:
<input type="text" name="textOne" title="required">
Text Tw o:
As you can see the form trigger which calls the AJAX actions is set in the button using the
onClick method. Also note I’ve added title=”required” to the ‘textOne’ field - this means the user
will not be able to submit the form unless this field contains a value.
Finally here is a very stripped down Server script in PHP which takes the form values and
returns them formatted back to the JS (you could do anything with the data at this stage!).
process.php
view plainprint?
1. if(isset($_GET['rnd982g'])) {
2. foreach($_GET as $a => $b) {
3. if($a == "rnd982g") {
4. // ignore this random number
5. // only used to prevent browser caching
6. } else {
7. echo "<b>$a</b>: ".stripslashes(htmlentities($b))." ";
8. } // if
9. } //foreach
10. die;
11. }
if(isset($_GET['rnd982g'])) {
foreach($_GET as $a => $b) {
if($a == "rnd982g") {
// ignore this random number
// only used to prevent brow ser caching
} else {
echo "<b>$a</b>: ".stripslashes(htmlentities($b))." ";
} // if
} //foreach
die;
You could easily change the above to generate an email or add the form data to a database, the
above example will echo out the results which are passed back to the div tag below the form.
There you have it, short and sweet (I hope) - I’ve intentionally kept the example scripts to a
minumum but with still enough to be useful. Please feel free to take this and mess around with it.
EXT JS Javascript with Ajax
1. /*
2. * Ext JS Library 1.0.1
3. * Copyright(c) 2006-2007, Ext JS, LLC.
4. * licensing@extjs.com
5. *
6. * http://www.extjs.com/license
7. */
8.
9. Ext.onReady(function(){
10.
11. // create the Data Store
12. var ds = new Ext.data.Store({
13. // load using HTTP
14. proxy: new Ext.data.HttpProxy({url: 'sheldon.xml'}),
15.
16. // the return will be XML, so lets set up a reader
17. reader: new Ext.data.XmlReader({
18. // records will have an "Item" tag
19. record: 'Item',
20. id: 'ASIN',
21. totalRecords: '@total'
22. }, [
23. // set up the fields mapping into the xml doc
24. // The first needs mapping, the others are very basic
25. {name: 'Author', mapping: 'ItemAttributes > Author'},
26. 'Title', 'Manufacturer', 'ProductGroup'
27. ])
28. });
29.
30. var cm = new Ext.grid.ColumnModel([
31. {header: "Author", width: 120, dataIndex: 'Author'},
32. {header: "Title", width: 180, dataIndex: 'Title'},
33. {header: "Manufacturer", width: 115, dataIndex: 'Manufacturer'
},
34. {header: "Product Group", width: 100, dataIndex: 'ProductGroup
'}
35. ]);
36. cm.defaultSortable = true;
37.
38. // create the grid
39. var grid = new Ext.grid.Grid('example-grid', {
40. ds: ds,
41. cm: cm
42. });
43. grid.render();
44.
45. ds.load();
46. });