Thursday, April 26, 2018

AJAX - Send a Request To a Server


AJAX - Send a Request To a Server

The XML Http Request object is used to exchange data with a server.

Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XML Http Request object:

xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method   Description
open(method, url, async) Specifies the type of request

method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string)  Sends the request to the server (used for POST)
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no size limitations).
Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
GET Requests
A simple GET request:

Example
xhttp.open("GET", "demo_get.html", true);
xhttp.send();
»
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:

Example
xhttp.open("GET", "demo_get.html?t=" + Math.random(), true);
xhttp.send();
»
If you want to send information with the GET method, add the information to the URL:

Example
xhttp.open("GET", "demo_get2.html?fname=Henry&lname=Ford", true);
xhttp.send();

POST Requests
A simple POST request:

Example
xhttp.open("POST", "demo_post.html", true);
xhttp.send();
»
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

Example
xhttp.open("POST", "ajax_test.html", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
»
Method   Description
setRequestHeader(header, value)    Adds HTTP headers to the request

header: specifies the header name
value: specifies the header value
The url - A File On a Server
The url parameter of the open() method, is an address to a file on a server:

xhttp.open("GET", "ajax_test.html", true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .html and .php (which can perform actions on the server before sending the response back).

Asynchronous - True or False?
To send the request asynchronously, the async parameter of the open() method has to be set to true:

xhttp.open("GET", "ajax_test.html", true);
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.

By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:

execute other scripts while waiting for server response
deal with the response when the response ready
Async = true
When using async = true, specify a function to execute when the response is ready in the onreadystatechange event:

Example
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
»
You will learn more about onreadystatechange in a later chapter.
Async = false
To use async = false, change the third parameter in the open() method to false:

xhttp.open("GET", "ajax_info.txt", false);
Using async = false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async = false, do NOT write an onreadystatechange function - just put the code after the send() statement:

Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;




AJAX - The XML Http Request Object


AJAX - The XML Http Request Object

The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object
All modern browsers (Chrome, IE7+, Firefox, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:

variable = new ActiveXObject("Microsoft.XMLHTTP");
To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:

Example
var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
»
Access Across Domains
For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

The examples on Omegas all open XML files located on the Omegas domain.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

Old Versions of Internet Explorer (IE5 and IE6)
Old versions of Internet Explorer (IE5 and IE6) do not support the XMLHttpRequest object.

To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object, or else create an ActiveXObject:

Example
if (window.XMLHttpRequest) {
    // code for modern browsers
    xmlhttp = new XMLHttpRequest();
 } else {
    // code for old IE browsers
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
»
XMLHttpRequest Object Methods
Method   Description
new XMLHttpRequest()     Creates a new XMLHttpRequest object
abort()     Cancels the current request
getAllResponseHeaders()  Returns header information
getResponseHeader()  Returns specific header information
open(method, url, async, user, psw)      Specifies the request

method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string)  Sends the request to the server.
Used for POST requests
setRequestHeader()     Adds a label/value pair to the header to be sent
XMLHttpRequest Object Properties
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
responseText     Returns the response data as a string
responseXML     Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference
statusText     Returns the status-text (e.g. "OK" or "Not Found")



JavaScript Cookies


JavaScript Cookies

Cookies let you store user information in web pages.

What are Cookies?
Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
Cookies are saved in name-value pairs like:

username = John Doe
When a browser requests a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookie property.

With JavaScript, a cookie can be created like this:

document.cookie = "username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:

var x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
The old cookie is overwritten.

Delete a Cookie with JavaScript
Deleting a cookie is very simple.

You don't have to specify a cookie value when you delete a cookie.

Just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
You should define the cookie path to ensure that you delete the right cookie.

Some browsers will not let you delete a cookie if you don't specify the path.

The Cookie String
The document.cookie property looks like a normal text string. But it is not.

Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.

If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:

cookie1 = value; cookie2 = value;

Display All Cookies  Create Cookie 1  Create Cookie 2 Delete Cookie 1  Delete Cookie 2

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

JavaScript Cookie Example
In the example to follow, we will create a cookie that stores the name of a visitor.

The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he will get a welcome message.

For the example we will create 3 JavaScript functions:

A function to set a cookie value
A function to get a cookie value
A function to check a cookie value
A Function to Set a Cookie
First, we create a function that stores the name of the visitor in a cookie variable:

Example
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Example explained:

The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.

A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:

Example
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Decode the cookie string, to handle cookies with special characters, e.g. '$'

Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(';')).

Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length).

If the cookie is not found, return "".

A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:

Example
function checkCookie() {
    var username = getCookie("username");
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }
}
All Together Now
Example
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}



JavaScript Window History


JavaScript Window History

The window.history object contains the browsers history.

Window History
The window.history object can be written without the window prefix.

To protect the privacy of the users, there are limitations to how JavaScript can access this object.

Some methods:

history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser
Window History Back
The history.back() method loads the previous URL in the history list.

This is the same as clicking the Back button in the browser.

Example
Create a back button on a page:

<html>
<head>
<script>
function goBack() {
    window.history.back()
}
</script>
</head>
<body>

<input type="button" value="Back" onclick="goBack()">

</body>
</html>

The output of the code above will be:


Window History Forward
The history forward() method loads the next URL in the history list.

This is the same as clicking the Forward button in the browser.

Example
Create a forward button on a page:

<html>
<head>
<script>
function goForward() {
    window.history.forward()
}
</script>
</head>
<body>

<input type="button" value="Forward" onclick="goForward()">

</body>
</html>