AJAX – Dynamic Versus Static Sites

Ajax – Dynamic Versus Static Sites ”; Previous Next Website is a collection of multiple but related web pages that contains multimedia content like text, images, videos, and audio. Each website present on the internet has their own separate URL through which we can access using web browsers. For example − https://www.tutorialspoint.com/. Website of two types − Static Website Dynamic Website Static Website A static website is a website in which the web pages returned by the server are prebuilt source code files that are written in simple HTML and CSS. The content of the static website is fixed, which means the content of the website can only be changed by the owner(manually) of the website, are allowed to change the content of the static website on the server side. Or we can say that static websites are those websites in which the content of the website can”t be manipulated or changed from the server”s side.. A static website does not require any scripting languages. For example, Dynamic Website A dynamic website is a website in which the content of the web pages is dynamic, which means the information on the website can change automatically according to the input given by the user. Dynamic websites required back-end databases and scripting languages like PHP, Node.js, etc. To get good flexibility dynamic website require a more complex back end. Examples of dynamic websites are Netflix, Facebook, Twitter, etc. Dynamic Versus Static Website Following are the difference between dynamic and static websites − Static Website Dynamic Website The content of the website can not be changed at runtime. The content of the website can be changed at runtime. There is no interaction with the database. It interacts with the database very efficiently. It loads faster on the web browser as compared to a dynamic website. It loads slower on the web browser as compared to a static website. Development cost is cheap. Development cost is high. It does not require a content management system. It required a content management system. It doesn”t require scripting languages. It required scripting languages. To develop a static website we required HTML, CSS, and Javascript. To develop a dynamic website we required web languages like HTML, CSS, and Javascript along with server-side languages like PHP, Node.js, etc. It delivers the same data/content every time the page loads. It can deliver different content/data every time the page loads. It has poor scalability. It has good scalability. Conclusion So these are the major differences between dynamic and static websites. Hence developers and users prefer dynamic websites over static websites. Now in the next article, we will learn about AJAX technologies. Print Page Previous Next Advertisements ”;

AJAX – Handling Responses

AJAX – Handling Responses ”; Previous Next AJAX is a technique which is used to send and receive data to and from the web server asynchronously without reloading or refreshing the whole page. When an AJAX application made an asynchronous request to the server from a web page, then the server responds to the request and returns the requested data, so the receiving and handling of the server”s response are known as handling responses. Or we can say that handling responses is a process that deals with the returned data from the server, performs appropriate operations on it, and updates the web page accordingly. Handling responses covers the following points − Receiving Response − Once the AJAX send the request to the server, then the client-side JS code waits for the server response. When the server responds to the request, the response is returned to the client. Process Response − After getting the response from the server, now the client-side JS process the data in the expected format because the data returned by the server is in various formats like JSON, XML, etc., and also extracts only related information from the response. Updateding Web application/ web page − After processing the response AJAX callback function updates the web page or web application dynamically according to the response. It includes modifying HTML content, displaying error messages, updating the values, etc. Handle Error − If the request meets an error, then the server may respond with an error status due to any request failure, network issue, etc. So the Handling response process handles the error very efficiently and takes proper action against the error. How to handle responses works Follow the following steps to handle the responses using XMLHttpRequest − Step 1 − Create an XMLHttpRequest object using XMLHttpRequest() constructor. Using this object you can easily do HTTP requests and can handle their responses asynchronously. var qhttp = new XMLHttpRequest(); Step 2 − Define an event handler for the readystatechange event. This event trigger whenever the value of the readyState property of the XHR object changes. qhttp.onreadystatechange = function() { if (qhttp.readyState == 4){ if(qhttp.status == 200){ // Display the response }else{ // Handle the error if occure } } }; Step 3 − Open the request by using the HTTP method(like GET, POST, etc) and the URL which we want to request. qhttp.open(“HTTP Method”,”your-URL”, true); Step 4 − Set any header if required. qhttp.setRequestHeader(”Authorization”, ”Your-Token”); Step 5 − Send the request to the server. qhttp.send() Example In the following program, we will handle the response returned by the server on the given request. So for that, we will create a Javascript function named as handleResponse() which handles the response returned by the server and display the result accordingly. This function first creates an XMLHttpRequest object, and then it defines an “onreadystatechange” event handler to handle the request state. When the request state changes, then the function checks if the request is complete(readyState = 4). If the request is complete, then the function checks the status code = 200. If the status code is 200, then display the response. Otherwise, display the error message. <!DOCTYPE html> <html> <body> <script> function handleResponse() { // Creating XMLHttpRequest object var qhttp = new XMLHttpRequest(); // Creating call back function qhttp.onreadystatechange = function() { if (qhttp.readyState == 4){ if(qhttp.status == 200){ // Display the response console.log(qhttp.responseText) }else{ console.log(“Found Error: “, qhttp.status) } } }; // Open the given file qhttp.open(“GET”, “https://jsonplaceholder.typicode.com/todos”, true); // Sending request to the server qhttp.send() } </script> <h2>Display Data</h2> <button type=”button” onclick=”handleResponse()”>Submit</button> <div id=”sample”></div> </body> </html> Output Conclusion So this is how an AJAX can handle the response returned by the server due to which web pages can easily communicate with the server in the background asynchronously without refreshing the whole page. Now in the next article, we will learn how to handle binary data in the AJAX. Print Page Previous Next Advertisements ”;

AJAX – Types of requests

AJAX – Types of Requests ”; Previous Next AJAX is a web technology that is used to create dynamic web pages. It allows web pages to update their content without reloading the whole page. Generally, AJAX supports four types of requests and they are − GET request POST request PUT request DELETE request GET Request The GET request is used to retrieve data from a server. In this request, the data is sent as a part of the URL that is appended at the end of the request. We can use this request with the open() method. Syntax open(GET, url, true) Where, the open() method takes three parameters − GET − It is used to retrieve data from the server. url − url represents the file that will be opened on the web server. true − For asynchronous connection set the value to true. Or for synchronous connection set the value to false. The default value of this parameter is true. Example <!DOCTYPE html> <html> <body> <script> function displayRecords() { // Creating XMLHttpRequest object var zhttp = new XMLHttpRequest(); // Creating call back function zhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(“example”).innerHTML = this.responseText; } }; // Open the given file zhttp.open(“GET”, “https://jsonplaceholder.typicode.com/todos/6″, true); // Sending the request to the server zhttp.send(); } </script> <div id=”example”> <p>Please click on the button to fetch 6th record from the server</p> <button type=”button” onclick=”displayRecords()”>Click Here</button> </div> </body> </html> Output In the above example, we are fetching the 6th record from the server using the GET request “https://jsonplaceholder.typicode.com/todos/6” API in XMLHttpRequest. So after clicking on the button, we will get the 6th record from the server. POST Request The POST request is used to send data from a web page to a web server. In this request, the data is sent in the request body that is separated from the URL. We can use this request with the open() method. Syntax open(”POST”, url, true) Where, the open() method takes three parameters − POST − It is used to send data to the web server. url − url represents the server(file) location. true − For asynchronous connection set the value to true. Or for synchronous connection set the value to false. The default value of this parameter is true. Example <!DOCTYPE html> <html> <body> <script> function sendDoc() { // Creating XMLHttpRequest object var qhttp = new XMLHttpRequest(); // Creating call back function qhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 201) { document.getElementById(“sample”).innerHTML = this.responseText; console.log(“Data Send Successfully”) } }; // Open the given file qhttp.open(“POST”, “https://jsonplaceholder.typicode.com/todos”, true); // Setting HTTP request header qhttp.setRequestHeader(”Content-type”, ”application/json”) // Sending the JSON document to the server qhttp.send(JSON.stringify({ “title”: “MONGO”, “userId”: 11, “id”: 21, “body”: “est rerum tempore” })); } </script> <h2>Example of POST Request</h2> <button type=”button” onclick=”sendDoc()”>Post Data</button> <div id=”sample”></div> </body> </html> Output Here in the above example, we are updating the record with the below-given data using the PUT request. “https://jsonplaceholder.typicode.com/todos/21” API: { “title”: “MONGO”, “userId”: 11, “id”: 21, “body”: “est rerum tempore” } DELETE Request The DELETE request is used to delete data from the web server. In this request, the data to be deleted is sent in the request body and the web server will delete that data from its storage. Syntax open(”DELETE”, url, true) Where, the open() method takes three parameters − DELETE − It is used to delete data from the web server. url − It represents the file url which will be opened on the web server. Or we can say server(file) location. true − For asynchronous connection set the value to true. Or for synchronous connection set the value to false. The default value of this parameter is true. Example <!DOCTYPE html> <html> <body> <script> function delDoc() { // Creating XMLHttpRequest object var qhttp = new XMLHttpRequest(); // Creating call back function qhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(“sample”).innerHTML = this.responseText; console.log(“Record Deleted Successfully”) } }; // Deleting given file qhttp.open(“DELETE”, “https://jsonplaceholder.typicode.com/todos/2″, true); // Sending the request to the server qhttp.send(); } </script> <div id=”sample”> <h2>Example of DELETE Request</h2> <button type=”button” onclick=”delDoc()”>Deleteing Data</button> </div> </body> </html> Output Here in the above example, we delete the record present on Id = 2 using the DELETE request “https://jsonplaceholder.typicode.com/todos/2” API. AJAX also support some other request like OPTIONS, HEAD, and TRACE but they are the least commonly used requests by the AJAX applications. Now in the next article, we will see how AJAX handle responses. Print Page Previous Next Advertisements ”;

AJAX – XMLHttpRequest

AJAX – XMLHttpRequest ”; Previous Next In AJAX, XMLHttpRequest plays a very important role. XMLHttpRequest is used to exchange data to or from the web server in the background while the user/client working in the foreground and then update the part of the web page with the received data without reloading the whole page. We can also say that XMLHttpRequest (XHR) can be used by various web browser scripting languages like JavaScript, JScript, VBScript, etc., to exchange XML data to or from the web server with the help of HTTP. Apart from XML, XMLHttpRequest can also fetch data in various formats like JSON, etc. It creates an asynchronous connection between the client side and the server side. Syntax variableName = new XMLHttpRequest() Where using a new keyword along with XMLHttpRequest() constructor we can be able to create a new XMLHttpRequest object. This object must be created before calling the open() function to initialise it before calling send() function to send the request to the web server. XMLHttpRequest Object Methods XMLHttpRequest object has the following methods − Sr.No. Method Name & Description 1 new XMLHttpRequest() It is used to create an XMLHttpRequest() object 2 getAllResponseHeaders() It is used to get the header information 3 getResponseHeader() It is used to get the specific header information 4 open(method, url, async, user, psw) It is used to initialise the request parameters. Here, method: request type GET or POST or Other types url: file location async: for the asynchronous set to true or for synchronous set to false user: for optional user name psw: for optional password 5 send() It is used to send requests to the web server. It is generally used for GET requests. 6 send(string) It is used to send requests to the server. It is generally used for POST requests. 7 setRequestHeader() It is used to add key/value pair to the header XMLHttpRequest Object Properties XMLHttpRequest object has the following properties − Sr.No. Property Name & Description 1 onreadystatechange Set the callback function which handles request state changes. 2 readyState It is used to hold the status of XMLHttpRequest. It has the following values − It represents the request is not initialise It represents the server connection established It represents the request received It represents the request is in processing It represents the request finished and the response is ready 3 responseText It is used to return the response data as a string 4 responseXML It is used to return the response data as XML data 5 Status It is used to return the status number of a request. For example − 200: for OK 403: for Forbidden 404: for Not Found 6 StatusText It is used to return the status text. For example, OK, Not Found, etc. Usage of XMLHttpRequest After understanding the basic syntax, methods, and properties of XMLHttpRequest now we learn how to use XMLHttpRequest in real life. So to use XMLHttpRequest in your program first we need to follow the following major steps − Step 1 − Create an object of XMLHttpRequest var variableName = new XMLHttpRequest() Step 2 − After creating XMLHttpRequest an object, we now have to define a callback function which will trigger after getting a response from the web server. XMLHttpRequestObjectName.onreadystatechange = function(){ // Callback function body } XMLHttpRequestObjectName.open(method, url, async) XMLHttpRequestObjectName.send() Step 3 − Now we use open() and send() functions to send a request to the web server. Now lets us understand the working of XMLHttpRequest with the help of the following example− Example In the below example, we are going to fetch data from the server. To fetch the data from the server we will click on the “Click Me” button. So when we click on the “Click Me” button, the displayDoc() function is called. Inside the displayDoc() function, we create an XMLHttpRequest object. Then we create a call-back function to handle the server response. Then we call the open() method of the XHR object to initialise the request with HTTP GET method and the server URL which is “https://jsonplaceholder.typicode.com/todos”. Then we call send() function to send the request. So when the server responds to the request, the “onreadystatechange” property calls the callback function with the current state of XMLHttpRequest object. If the “ready state” property is set to 4(that means the request is completed) and the “status” property is set to 200(that means the successful response), then the response data is extracted from the “responseText” property and display the HTML document with the help of “innerHTML” property of the sample element. If we error is found during the request then the else statement present in the callback function will execute. So this is how we can fetch data from the server. <!DOCTYPE html> <html> <body> <script> function displayDoc() { // Creating XMLHttpRequest object var myObj = new XMLHttpRequest(); // Creating a callback function myObj.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(“sample”).innerHTML = this.responseText; }else{ console.log(“Error Found”) } }; // Open the given file myObj.open(“GET”, “https://jsonplaceholder.typicode.com/todos”, true); // Sending the request to the server myObj.send(); } </script> <div id=”sample”> <h2>Getting Data</h2> <p>Please click on the button to fetch data</p> <button type=”button” onclick=”displayDoc()”>Click Me</button> </div> </body> </html> Output Conclusion XMLHttpRequest is the main object of AJAX through which AJAX create asynchronous communication between

AJAX – History

Ajax – History ”; Previous Next Before the introduction of AJAX, websites are developed by adding multiple loose web pages together, which are further displayed in a predefined order with the help of links embedded inside the HTML pages. So to use these web application user needs to move from one web page to another web page. So whenever the user clicks on a link to the next page he/she should wait for some seconds for a page to be loaded. Traditional web applications use HTTP requests to submit user action to the server. After receiving the request from the user the web server completes the request by returning a new web page which will further display on the web browser. Hence traditional web applications required lots of page refreshes and waiting. Due to this, it is very hard to develop new-generation applications like google maps, real-time chatting environment, Gmail, etc. So on 18 February 2005 for the first time, Jesse James Garrett introduce AJAX to the world by writing an AJAX article named “A New Approach to Web Application”. And on 5th April 2006, the W3C(world wide web consortium) release the first draft which contains the specifications for the XMLHttpRequest object. After that AJAX will be popular among web developers. The applications developed by using AJAX are faster and more responsive as compared to traditional web applications. It improves the performance of web applications by exchanging a small amount of data to the web servers. As a result, there is no need for the servers to refresh the entire web page for every request of the user. That means using AJAX the web browser and the web server can exchange data asynchronously in the background without pausing the execution of the application and can process the returned data. To submit requests AJAX application uses a special object known as XMLHttpRequest object. It is the main object due to which AJAX can able to create asynchronous communication. And the technologies used in implementing AJAX are JavaScript, XMLHttpRequest, XML/JSON, and Document Object Model(DOM). Here Javascript handles client-side logic, XHR provides asynchronous communication with the server, XML provides a format for data interchange between the server and the client, and DOM allows manipulation and updation of the content of the web pages. Conclusion So this is how the introduction of AJAX creates a new revolution in the web development industry. It helps developers to create rich and interactive web applications. Now in the next article, we will learn how dynamic websites are different from static websites. Print Page Previous Next Advertisements ”;