Hi, this is a basic level AJAX tutorial for beginners. This AJAX guide will help you to do a fresh start of working with AJAX from beginning. In this AJAX tutorial, you will know what is AJAX, how AJAX works, how to prepend and append data in a web page without reloading it and more…
What is AJAX?
AJAX stands for Asynchronous JavaScript And XML. AJAX is not a different programming language, but AJAX is combination of Web Technologies. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object.
Required skills to learn AJAX
AJAX is bunch of technologies combined to interact with server without reloading the page. Before we start learning AJAX, you need to be familiar with the technologies below. more on Wikipedia…
- HTML (or XHTML) and CSS for presentation
- The Document Object Model (DOM) for dynamic display of and interaction with data
- XML for the interchange of data, and XSLT for its manipulation
- The XMLHttpRequest object for asynchronous communication
- JavaScript to bring these technologies together
Available Tutorials on JavaScript, HTML, CSS & XML
You can easily learn JavaScript, HTML, CSS and XML in very short amount of time from links below.
- JavaScript Tutorial – a Beginner’s JavaScript Guide
- HTML Tutorial – Learn HTML in One Day – for Beginners
- CSS Tutorial – a Beginner’s CSS Guide Part 1
- CSS Tutorial – Advance user’s CSS guide Part 2
- XML Tutorial – a Beginner’s XML Guide
An XMLHttpRequest (case sensitive) by AJAX
Properties
readyState
responseText
responseXML
status
statusText
Event Handler
onreadystatechange
1.1. readyState
Value | Definition |
---|---|
1 | Uninitialized – Object contains no data. |
2 | Loading – Object is currently loading data. |
3 | Loaded – Object has finished loadin it’s data. |
4 | Inter-Active – Users may interact with the object even it’s not fully loaded. |
5 | Complete – Object has finished initializing. |
1.2. responseText
To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object. The responseText property returns the response as a string, and you can use it as below.
document.getElementById("div1").innerHTML=xhr.responseText;
1.3. responseXML
If the response from the server is XML, and you want to parse it as an XML object, and use the responseXML property. Example:
xmlDoc = xhr.responseXML; txt = ""; xml = xmlDoc.getElementsByTagName("Names"); for (i = 0; i < xml.length; i++) { txt = txt + xml[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("div1").innerHTML = txt;
1.4. status
When we sent request to a server, we need to perform some actions based on the response from server.
Value | Definition |
---|---|
200 | OK. |
400 | Bad request. |
401 | Unauthorised. |
403 | Forbidden. |
404 | Not found. |
1xx status codes are informational, 2xx codes are about success, 3xx codes are about redirection, 4xx codes are about client error and the 5xx codes are about server error. You can get all error codes and their details here (wikipedia)…
1.5. statusText
It returns the status-text (e.g. “Not Found” or “OK”).
2.1. onreadystatechange
The onreadystatechange event is triggered every time the readyState changes.
XMLHttpRequest Methods
Method | Description |
---|---|
abort() | Abort current request. |
getAllResponseHeaders() | Ask server for all response headers. |
getResponseHeader(“header-name”) | Get a particular response header. |
open(“method”, “url”, “async T/F”, “user”, “password”) | The type of request, url, request is asynchronously or not and user password are optional. |
send(“content”) | Send request to the server. |
setRequestHeader(“label”, “value”) | Set specific header on request sending to server. |
Template Script
<html> <head> <script type="text/javascript"> function loadXMLDoc(){ var xhr; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xhr=new XMLHttpRequest(); } else {// code for IE6, IE5 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } xhr.onreadystatechange=function() { if (xhr.readyState==4 && xhr.status==200) { document.getElementById("myDiv").innerHTML=xhr.responseText; } } xhr.open("GET","info.txt",true); xhr.send(); } </script> </head> <body> <div id="myDiv"> <p>Let AJAX change this text!</p> </div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
More on AJAX
Do you want to learn more about AJAX? You can learn how to load/fetch/parse content in a web page from different file types like XML, JSON, Text Files by jQuery AJAX from here – How to Load Content from XML, JSON, Text File by jQuery AJAX
Having Problem with learning AJAX, need help? Just comment below, I’ll be back to you.
Thank you!
hola .. se ve muy bueno .. pero no me funciona o he pusteo asiCarga de datosfunction Carga(url,id){//Creamos un objeto dependiendo del navegadorvar objeto;if (window.XMLHttpRequest){//Mozilla, Safari, etcobjeto = new XMLHttpRequest();}else if (window.ActiveXObject){//Nuestro querido IEtry {objeto = new ActiveXObject( Msxml2.XMLHTTP );} catch (e) {try { //Version mas antiguaobjeto = new ActiveXObject( Microsoft.XMLHTTP );} catch (e) {}}}if (!objeto){alert( No ha sido posible crear un objeto de XMLHttpRequest );}//Cuando XMLHttpRequest cambie de estado, ejecutamos esta funcionobjeto.onreadystatechange=function(){cargarobjeto(objeto,id)}objeto.open( GET’, url, true) // indicamos con el me9todo open la url a cargar de manera asedncronaobjeto.send(null) // Enviamos los datos con el metodo send}
Sorry man, I can’t understand you. English please… Thank you.
Good post! It is rare to find tutorial this low level. Most guides are using some JS frameworks.