Welcome to the next article where we will discuss the basics of this, what changed JavaScript for ever.
Basics of AJAX
The AJAX (Asynchronous JavaScript and XML) — is a technology of web application development, in which the user can interact with the server without reloading the entire document. Operations are done asynchronously.
AJAX technology consists of several elements:
– XMLHttpRequest — an object allowing asynchronous transmission of data over the network. During processing the user can perform other tasks, also retrieve data from multiple sources.
– JavaScript — the language well known to us, although in the assumption it could be a different client-side language with DOM support, e.g. VBScript.
– XML — markup language as data carrier of sent and/or received information. In addition to the XML also other formats are used, such as JSON, although the data carrier can also be plain text or HTML snippets. For the Ajax with JSON there is even a special term: AJAJ.
Practical AJAX
Below we presented a basic example of using AJAX. Classical, in pure JavaScript i.e. without frameworks.
var httpRequest; if (window.XMLHttpRequest) { // Mozilla, Safari, … httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } httpRequest = new XMLHttpRequest(); httpRequest.overrideMimeType('text/xml'); // define a getter function: httpRequest.onreadystatechange = name; // or another way: httpRequest.onreadystatechange = function() { // definition alert('Test'); };
The open() method:
// true in the 3rd parameter = the request is asynchronous httpRequest.open('GET', 'http://www.example.org/some.file', true);
Examples of using the open() method:
r.open('GET', 'mysite.jsp', true); r.open('GET', 'myfile.jpg', true); r.open('GET', 'http://www.example.net/get.php?id=123', true);
Sending the data — send():
httpRequest.send(null);
The send() method has one parameter: data appended to the query. This parameter must be used for the POST method. We use null if the method used is GET.