JavaScript Ajax GET Demo

AJAX — Server Response

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: «OK»
403: «Forbidden»
404: «Page not found»
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. «OK» or «Not Found»)

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example

The «ajax_info.txt» file used in the example above, is a simple text file and looks like this:

AJAX

AJAX is not a programming language.

AJAX is a technique for accessing web servers from a web page.

AJAX stands for Asynchronous JavaScript And XML.

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

Using a Callback Function

A callback function is a function passed as a parameter to another function.

If you have more than one AJAX task in a website, you should create one function for executing the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is ready.

Example

function loadDoc(url, cFunction) var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() if (this.readyState == 4 && this.status == 200) cFunction(this);
>
>;
xhttp.open(«GET», url, true);
xhttp.send();
>

function myFunction1(xhttp) // action goes here
>
function myFunction2(xhttp) // action goes here
>

Server Response Properties

Property Description
responseText get the response data as a string
responseXML get the response data as XML data

Server Response Methods

Method Description
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders() Returns all the header information from the server resource

The responseText Property

The responseText property returns the server response as a JavaScript string, and you can use it accordingly:

Example

The responseXML Property

The XML HttpRequest object has an in-built XML parser.

The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Example

Request the file cd_catalog.xml and parse the response:

xmlDoc = xhttp.responseXML;
txt = «»;
x = xmlDoc.getElementsByTagName(«ARTIST»);
for (i = 0; i < x.length; i++) txt += x[i].childNodes[0].nodeValue + "
«;
>
document.getElementById(«demo»).innerHTML = txt;
xhttp.open(«GET», «cd_catalog.xml», true);
xhttp.send();

You will learn a lot more about XML DOM in the DOM chapters of this tutorial.

The getAllResponseHeaders() Method

The getAllResponseHeaders() method returns all header information from the server response.

Example

The getResponseHeader() Method

The getResponseHeader() method returns specific header information from the server response.

Источник

JavaScript Ajax

In this tutorial you will learn what Ajax is and how to implement it in JavaScript.

What is Ajax?

Ajax stands for Asynchronous Javascript And Xml. Ajax is just a means of loading data from the server and selectively updating parts of a web page without reloading the whole page.

Basically, what Ajax does is make use of the browser’s built-in XMLHttpRequest (XHR) object to send and receive information to and from a web server asynchronously, in the background, without blocking the page or interfering with the user’s experience.

Ajax has become so popular that you hardly find an application that doesn’t use Ajax to some extent. The example of some large-scale Ajax-driven online applications are: Gmail, Google Maps, Google Docs, YouTube, Facebook, Flickr, and so many other applications.

Note: Ajax is not a new technology, in fact, Ajax is not even really a technology at all. Ajax is just a term to describe the process of exchanging data from a web server asynchronously through JavaScript, without refreshing the page.

Tip: Don’t get confused by the term X (i.e. XML) in AJAX. It is only there for historical reasons. Other data exchange format such as JSON, HTML, or plain text can be used instead of XML.

Understanding How Ajax Works

To perform Ajax communication JavaScript uses a special object built into the browser—an XMLHttpRequest (XHR) object—to make HTTP requests to the server and receive data in response.

All modern browsers (Chrome, Firefox, IE7+, Safari, Opera) support the XMLHttpRequest object.

The following illustrations demonstrate how Ajax communication works:

Ajax Illustration

Since Ajax requests are usually asynchronous, execution of the script continues as soon as the Ajax request is sent, i.e. the browser will not halt the script execution until the server response comes back.

In the following section we’ll discuss each step involved in this process one by one:

Sending Request and Retrieving the Response

Before you perform Ajax communication between client and server, the first thing you must do is to instantiate an XMLHttpRequest object, as shown below:

Now, the next step in sending the request to the server is to instantiating the newly-created request object using the open() method of the XMLHttpRequest object.

The open() method typically accepts two parameters— the HTTP request method to use, such as «GET», «POST», etc., and the URL to send the request to, like this:

Tip: The file can be of any kind, like .txt or .xml , or server-side scripting files, like .php or .asp , which can perform some actions on the server (e.g. inserting or reading data from database) before sending the response back to the client.

And finally send the request to the server using the send() method of the XMLHttpRequest object.

Note: The send() method accepts an optional body parameter which allow us to specify the request’s body. This is primarily used for HTTP POST requests, since the HTTP GET request doesn’t have a request body, just request headers.

The GET method is generally used to send small amount of data to the server. Whereas, the POST method is used to send large amount of data, such as form data.

In GET method, the data is sent as URL parameters. But, in POST method, the data is sent to the server as a part of the HTTP request body. Data sent through POST method will not visible in the URL.

See the chapter on HTTP GET vs. POST for a detailed comparison of these two methods.

In the following section we’ll take a closer look at how Ajax requests actually works.

Performing an Ajax GET Request

The GET request is typically used to get or retrieve some kind of information from the server that doesn’t require any manipulation or change in database, for example, fetching search results based on a term, fetching user details based on their id or name, and so on.

The following example will show you how to make an Ajax GET request in JavaScript.

Example

        

Content of the result DIV box will be replaced by the server response

When the request is asynchronous, the send() method returns immediately after sending the request. Therefore you must check where the response currently stands in its lifecycle before processing it using the readyState property of the XMLHttpRequest object.

The readyState is an integer that specifies the status of an HTTP request. Also, the function assigned to the onreadystatechange event handler called every time the readyState property changes. The possible values of the readyState property are summarized below.

Value State Description
0 UNSENT An XMLHttpRequest object has been created, but the open() method hasn’t been called yet (i.e. request not initialized).
1 OPENED The open() method has been called (i.e. server connection established).
2 HEADERS_RECEIVED The send() method has been called (i.e. server has received the request).
3 LOADING The server is processing the request.
4 DONE The request has been processed and the response is ready.

Note: Theoretically, the readystatechange event should be triggered every time the readyState property changes. But, most browsers do not fire this event when readyState changes to 0 or 1. However, all browsers fire this event when readyState changes to 4 .

The status property returns the numerical HTTP status code of the XMLHttpRequest’s response. Some of the common HTTP status codes are listed below:

  • 200 — OK. The server successfully processed the request.
  • 404 — Not Found. The server can’t find the requested page.
  • 503 — Service Unavailable. The server is temporarily unavailable.

Please check out the HTTP status codes reference for a complete list of response codes.

Here’s the code from our «greet.php» file that simply creates the full name of a person by joining their first name and last name and outputs a greeting message.

Example

Performing an Ajax POST Request

The POST method is mainly used to submit a form data to the web server.

The following example will show you how to submit form data to the server using Ajax.

Example

        

Content of the result DIV box will be replaced by the server response

If you are not using the FormData object to send form data, for example, if you’re sending the form data to the server in the query string format, i.e. request.send(key1=value1&key2=value2) then you need to explicitly set the request header using setRequestHeader() method, like this:

The setRequestHeader() method, must be called after calling open() , but before calling send() .

Some common request headers are: application/x-www-form-urlencoded , multipart/form-data , application/json , application/xml , text/plain , text/html , and so on.

Note: The FormData object provides an easy way to construct a set of key/value pairs representing form fields and their values which can be sent using XMLHttpRequest.send() method. The transmitted data is in the same format that the form’s submit() method would use to send the data if the form’s encoding type were set to multipart/form-data .

Here’s the code of our «confirmation.php» file that simply outputs the values submitted by the user.

Example

Hi, $name. Your comment has been received successfully.

"; echo "

Here's the comment that you've entered: $comment

"; > else < echo "

Please fill all the fields in the form!

"; > > else < echo "

Something went wrong. Please try again.

"; > ?>

For security reasons, browsers do not allow you to make cross-domain Ajax requests. This means you can only make Ajax requests to URLs from the same domain as the original page, for example, if your application is running on the domain «mysite.com», you cannot make Ajax request to «othersite.com» or any other domain. This is commonly known as same origin policy.

However, you can load images, style sheets, JS files, and other resources from any domain.

Tip: Check out the jQuery Ajax methods for quick and seamless Ajax implementation. The jQuery framework provides very convenient methods to implement Ajax functionality.

Источник

Читайте также:  Php check mysql connections
Оцените статью