Fetch API – Request ”; Previous Next In Fetch API, Request interface is used to create a resource request. It is an alternative way of creating requests other than the fetch() function. It also provides various properties and methods which we can apply to the request. So, first, we will learn about Request() constructor, then how to send requests and then the method and properties provided by the Request interface. Constructor To create a request object we can use Request() constructor along with a new keyword. This constructor contains one mandatory parameter which is the URL of the resource and the other parameter is optional. Syntax const newRequest = new Request(resourceURL) Or const newRequest = new Request(resourceURL, optional) The Request() constructor has the following parameters − resourceURL − The resource which we want to fetch. Its value can be either a resource URL or the Request object. Options − Object which provides additional settings for the request and the customized options are as follows − method − Represents the request methods like GET, POST, PUT and DELETE. headers − Set a header to the request. body − Adding data to the request. This parameter is not used by GET or HEAD methods. mode − Set the mode for the request such as cors, same-origin, no-cors or navigate. By default the value of the mode parameter is cors. credentials − It sets the credentials which you want to use for the request such as omit, same-origin, or include. The default value of this parameter is same-origin. cache − Set the cache mode you want for your request. redirect − Used for redirect mode such as follow, error, or manual. By default, the parameter is set for follow value. referrer − A string which represents the referrer of the request such as client, URL, or no-referrer. The default value of this parameter is about the client. referrerPolicy − Used to set the referrer policy. integrity − Used to set the subresource integrity value of the given request. keepalive − Used to check whether to create a persistent connection for multiple requests/response or not. signal − Represent an AbortSignal object which is used to communicate with or abort a request. priority − Used to set the priority of the request as compared to other requests. The possible value of this parameter is: high − Set the priority of the current fetch request to high as compared to others. low − Set the priority of the current fetch request to low as compared to others. auto − Automatically find the priority of the current fetch request. Send Request To send a request, we must first create a Request object using the Request constructor with additional parameters like header, body, method, resource URL, etc. Then pass this object in the fetch() function to send the request to the server. Now the fetch() function returns a promise which will resolve with the response object. If we encounter an error, then we execute the catch block. Example In the following program, we create a script to send data using the Request object. So for that, we create a request object using Request() constructor along with parameters like − URL − Represent the resource URL. method − Here we use the POST method which represents we are sending data to the server. body − Contains the data which we want to send. header − It tells that the data is JSON data. Now we pass the request object in the fetch() function to send the request and handle the response returned by the server and handle the error if it occurs. <!DOCTYPE html> <html> <body> <script> // Creating request object const myRequest = new Request(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request method: “POST”, // Add body which contains data body: JSON.stringify({ id: 321, title: “Kirti is a good girl”, }), // Setting header headers:{“Content-type”: “application/json; charset=UTF-8”} }); fetch(myRequest) // Handling response .then(response => response.json()) .then(myData => { console.log(“Data Sent Successfully”); // Display output document.getElementById(“sendData”).innerHTML = JSON.stringify(myData); }) // Handling error .catch(err=>{ console.error(“We get an error:”, err); }); </script> <h2>Fetch API Example</h2> <div> <!– Displaying retrieved data–> <p id=”sendData”></p> </div> </body> </html> Output Instance Properties The properties provided by the request interface are the read-only properties. So the commonly used properties are − Sr.No. Property & Description 1 Request.url This property contains the URL of the given request. 2 Request.body This property contains the body of the given request. 3 Request.bodyUsed This property is used to tell whether the body present in the request is used or not. Its value is boolean. 4 Request.destination This property is used to tell the destination of the request. 5 Request.method This property contains the request methods such as GET, POST, PUT, and DELETE. 6 Request.headers This property contains the header object of the request. 7 Request.cache This property contains the cache mode of the given request. 8 Request.credentials This property contains the credentials of the given request. 9 Request.mode This property contains the mode of the given request. Example In the following program, we use the properties (such as url, method, headers, and mode)provided by the Request interface. <!DOCTYPE html> <html> <head> <title>Fetch API Example</title> </head> <body> <h1>Example of Fetch API</h1> <script> // Creating request object const myRequest = new Request(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request method: “POST”, // Add body which contains data body: JSON.stringify({
Category: ajax
Fetch API Vs XMLHttpRequest
Fetch API Vs XMLHttpRequest ”; Previous Next An XMLHttpRequest object is used to communicate with the server asynchronously, which means we can exchange data to or from the server in the background without refreshing the whole page. XMLHttpRequest is the most commonly used technique that”s why it is used by most of the mainstream browsers like Google Chrome, Safari, Mozilla Firefox, or Opera. It also supports plain text, JSON data, and many more data formats. It is very easy to use and provides various methods and properties to perform operations. We can create an XMLHttpRequest object using XMLHttpRequest() constructor. Syntax variableName = new XMLHttpRequest() Where using a new keyword along with the XMLHttpRequest() constructor we are able to create a new XMLHttpRequest object. This object must be created before calling the open() function to initialize it before calling send() function to send the request to the web server. Fetch API provides an interface that is used to fetch/retrieve resources from the server. It is a modern alternative to XMLHttpRequest. It supports the generic definition of Request, and Response due to which we can access them in the future if required for Cache API, Service work, handling or modifying requests and responses, etc. It is very easy, simple and consistent. Or we can say that it provides a modern and flexible approach for creating HTTP requests and handling responses as compared to XMLHttpRequest. It is based on the Promise API which provides clear syntax and better error handling. Syntax fetch(res) Where fetch() takes one mandatory parameter which is res. The res parameter defines the resource that you want to fetch, it can be either a string or any other object or can be a request object. Apart from mandatory parameters, it can also take one optional parameter that can be either method, headers, body, mode cache, same-origin, etc. Fetch API VS XMLHttpRequest Following are the difference between the Fetch API and XMLHttpRequest − Difference Fetch API XMLHttpRequest Syntax As we know Fetch API is a promise-based API so it provides more clear syntax and better error-handling methods. XHR is based on a callback approach and its syntax is not as good as Fetch API. Cross-Origin Resource Sharing(CROS) Fetch API handle CROS request wisely without any additional configuration. XMLHttpRequest requires a special configuration to handle or make cross-origin requests. Request and Response Header Fetch API provides more flexible ways to work with request and response headers. XMLHttpRequest provides a limited number of methods to work with request and response headers. Streaming and Parsing Fetch API provides good support for streaming and parsing large responses, so it improves performance and reduces memory usage. XMLHttpRequest requires a custom program to get this functionality. Browser Compatibilities Fetch API is new so it may not be supported by older versions of the browsers. XMLHttpRequest has been used for many years so it is supported by almost all browsers. Cookies and Credential Control Fetch API provides good control over cookies and credentials due to which we can easily do authentication and authorisation as compared to XMLHttpRequest. XMLHttpRequest provide less support to cookies and credentials. Timeouts Fetch API does not support timeouts so the request will continue till the browser selects the request. XMLHttpRequest supports timeouts. Conclusion So these are the major difference between Fetch API and XMLHttpRequest. Fetch API is more powerful and easier to understand as compared to XMLHttpRequest. It is also supported by all modern browsers but XMLHttpRequest is only supported by old browsers. Now in the next article, we will learn about fetch() function. Print Page Previous Next Advertisements ”;
AJAX – Security
AJAX – Security ”; Previous Next AJAX is the most commonly used web technique to send and receive data to and from the web server asynchronously without disturbing the functionality of the other components of the client-side application. Although AJAX itself does not provide any security vulnerabilities, still we have to keep some security measurements while implementing AJAX. The security measurements are − Cross-Site Scripting(XSS) − AJAX applications should be vulnerable to XSS attacks. If proper input validation and output encoding are not implemented, then a hacker can easily inject malicious scripts inside the AJAX response. These malicious scripts are used to steal sensitive data from the system or can manipulate the content. So always create an AJAX application which is safe from this attack using proper validation and sanitization before displaying data on the web page. Cross-Site Request Forgery(CSRF) − In this attack, the attacker tricks the browser by doing unwanted actions with the help of an authentication session. It can exploit the AJAX request and can perform unauthorized actions. So to prevent this attack we have to implement CSRF protection techniques like generation and validating random tokens Or can use the same origin policy. Insecure Direct Object References(IDOR) − The request generally accesses the specified resource from the server with the help of a unique identifier. But if the attacker gets this identifier then it can easily manipulate or can access unauthorized resources. So to prevent this avoid exposing sensitive information. Also, check the user authorization for the specified resource of the developers, in the server side. Content Security Policies(CSP) − It is a policy which helps users/developers to save themselves from malicious activities or unauthorized access. It provides a permitted source for secure scripts and other resources. Server-Side validation − Server-side validation is very important because it ensures that the submitted data meets the specified criteria and it is safe for further process. We can not bypass or manipulate server-side validation but we can bypass client-side validation. Secure Session Management − The AJAX application should properly maintain user sessions and session tokens to save the session from attacks. Always check that the session tokes are generated properly, and securely transmitted and can logout if the invalidation or session expiration happens. Input Validation and Sanitization − Server should perform validation and sanitization of the data received from the client side to prevent attacks. Regular Update and Security − As we know that AJAX uses external libraries or frameworks. So keeping them up to date is an important task. To avoid various vulnerabilities and improve the security of the application. Conclusion So while creating an AJAX application always remember these points for security purposes to save your application from attacks. Now in the next article, we will the major issues faced by AJAX. Print Page Previous Next Advertisements ”;
AJAX – Home
AJAX Tutorial | Learn Ajax PDF Version Quick Guide Resources Job Search Discussion AJAX is a web development technique for creating interactive web applications. If you know JavaScript, HTML, CSS, and XML, then you need to spend just one hour to start with AJAX. Why to Learn Ajax? AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger. Data-driven as opposed to page-driven. Rich Internet Application Technology AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug. AJAX is Based on Open Standards AJAX is based on the following open standards − Browser-based presentation using HTML and Cascading Style Sheets (CSS). Data is stored in XML format and fetched from the server. Behind-the-scenes data fetches using XMLHttpRequest objects in the browser. JavaScript to make everything happen. Audience This tutorial will be useful for web developers who want to learn how to create interactive webpages as well as improve their speed and usability using AJAX. Prerequisites It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial. Frequently Asked Questions about AJAX There are some very Frequently Asked Questions(FAQ) about AJAX, this section tries to answer them briefly. What is AJAX and where do we use it? AJAX is an abbreviation that stands for Asynchronous JavaScript And XML. It enables interaction with a web page without the need for page reloading. Hence, it is used to enhance user experience. Who is the inventor of AJAX? The idea of AJAX was proposed by Jesse James Garrett in 2005. Which browser supports Ajax? Almost all modern browsers have built-in support for AJAX. The list includes Google Chrome, Mozilla Firefox, Safari, Microsoft Edge and Opera. How does Ajax Work? The following steps explain the working of AJAX − It starts with the occurrence of an event. Then, an XMLHttpRequest object is called, which sends a request to the server. The server receives and processes the request. The server sends the response back. In the end, the response is displayed on the screen. How can we test the AJAX code? The different ways to test AJAX code are as follows − End to end testing Manual testing Unit testing Using the browser”s built-in developer tools. Using testing frameworks How to Upload File in AJAX? To upload a file in AJAX, we use FormData object. Which companies use AJAX? Companies like Boeing, Dell, JPM Global, Amazon, Microsoft and many more use AJAX in different phases of the software development life cycle. What is the key component of AJAX? Following are the key components of AJAX are as follows − XMLHttpRequest object JavaScript HTML DOM How many data types are there in AJAX? AJAX does not have any data types. How to create AJAX objects? The AJAX objects are created using the XMLHttpRequest constructor of JavaScript. Print Page Previous Next Advertisements ”;
AJAX – Send POST Requests
AJAX – Send POST Requests ”; Previous Next The POST request sends 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. You cannot cache and bookmark Post requests. Also using POST request you can data of any length. Syntax open(”POST”, url, true) Where this method takes three parameters and they are − POST − It is used to send data to the web server. url − It represents the file url which will be opened on the web server. true − For asynchronous connection set this parameter”s value to true. Or for synchronous connection set the value to false. The default value of this parameter is true. How to use POST Request To use the POST request we need to follow the following steps − Step 1 − Create an object of XMLHttpRequest. var variableName = new XMLHttpRequest() Step 2 − After creating XMLHttpRequest an object, now we have to define a callback function which will trigger after getting a response from the web server. XMLHttpRequestObjectName.onreadystatechange = function(){ // Callback function body } Step 3 − Now we use open() functions. Inside the open() function we pass a POST request along with the URL to which we have to send data. XMLHttpRequestObjectName.open(“POST”, url, async) XMLHttpRequestObjectName.setRequestHeader(”Content-type”, ”application/json”) Step 4 − Set the HTTP header request using setRequestHeader(). It always calls after the open() method but before send() method. Here the content-type header is set to “application/json” which indicates that the data is going to send in JSON format. Step 5 − At last, we convert the JSON data into the string using stringify() method and then send it to the web server using send() method. XMLHttpRequestObjectName.send(JSON.stringify(JSONdata)) The following flow chart will show the working of the below code − Example <!DOCTYPE html> <html> <body> <script> function sendRecords() { // Creating XMLHttpRequest object var zhttp = new XMLHttpRequest(); // JSON document const mParameters = { title: document.querySelector(”#Utitle”).value, userid: document.querySelector(”#UId”).value, body: document.querySelector(”#Ubody”).value } // Creating call back function zhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 201) { document.getElementById(“example”).innerHTML = this.responseText; console.log(“Data Posted Successfully”) } console.log(“Error found”) }; // Post/Add JSON document on the given API zhttp.open(“POST”, “https://jsonplaceholder.typicode.com/todos”, true); // Setting HTTP request header zhttp.setRequestHeader(”Content-type”, ”application/json”) // Sending the request to the server zhttp.send(JSON.stringify(mParameters)); } </script> <!–Creating simple form–> <h2>Enter data</h2> <label for=”Utitle”>Title</label> <input id=”Utitle” type=”text” name=”title”><br> <label for=”UId”>UserId</label> <input id=”UId” type=”number” name=”UserID”><br> <label for=”Ubody”>Body</label> <input id=”Ubody” type=”text” name=”body”><br> <button type=”button” onclick=”sendRecords()”>Submit</button> <div id=”example”></div> </body> </html> initialise the request with the HTTP POST method and the URL of the server which is “https://jsonplaceholder.typicode.com/todos”. Then we call the setRequestHeader() method to set the content type of the request as JSON. After that, we call send() function to send the request along with a JSON document in the form of a string to the server. So when the server responds to the request, the “onreadystatechange” property calls the callback function with the current state of the XMLHttpRequest object. If the “ready state” property is set to 4(that means the request is completed) and the “status” property is set to 201(that means the server is successfully created a new resource), then the response data is extracted from the “responseText” property and display the HTML document with the help of “innerHTML” property of the example element. Here is the JSON.stringify() method is used to convert JSON documents into a string. It is necessary because XHR requests can only send text data. Difference between PUT and POST request Following is the difference between the PUT and the POST request − PUT Request POST Request It is used to update the existing record. It is used to create a new record. It sends the entire resource as a payload. It only sends the part to be updated. It can be cached It cannot be cached It is idempotent It is non-idempotent If we send this request multiple times then multiple URLs will be created on the specified server. If we send this request multiple times then multiple URLs will be created on the specified server If we send this request multiple times, still it counted as a single modification request by the server. Conclusion So this is how a POST request is sent by the XMLHttpRequest. It is the most commonly used method to send or post data to the server. Now in the next article, we will learn how to send a PUT request. Print Page Previous Next Advertisements ”;
AJAX – Technologies
AJAX – Technologies ”; Previous Next The full form of AJAX is asynchronous Javascript and XML. It is a combination of web technologies that allows to establish asynchronous communication between the web server and the web browser. It creates a dynamic application that updates the content of the webpage dynamically without reloading the whole page. AJAX is not a programming language or script language, but it combines multiple web-related technologies like HTML, XHTML, CSS, JavaScript, DOM, XML, XSLT and XMLHttpRequest object. Due to the combination of these technologies, the AJAX model allows web developers to create web applications that can dynamically interact with the user and can able to quickly make a background call to web servers to retrieve the required application data and then update the small portion of the web page without refreshing the whole web page. AJAX does not use any new language to create dynamic web applications, it uses the technologies that are already present in the market. So makes it easier for the developers to create a dynamic web application without learning or installing new technologies. Hence the web technologies used by the AJAX model are − Javascript − It is a scripting language for HTML and the web application. It creates a connection between HTML, CSS, and XML. It is used to create client-side functionality. It also plays an important role in AJAX. It is also used to create AJAX applications or join all the AJAX operations together. <script src = “myexample.js”></script> XML or JSON − XML stands for extensible markup language whereas JSON stands for JavaScript Object Notation. Both JSON and XML are used on the client side to exchange data between the web server and the client. <?xml version = “1.0”> <root> <child> //Statements </child> </root> XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server. It is a javascript object that performs asynchronous operations. variableName = new XMLHttpRequest(); HTML and CSS − HTML stands for hypertext markup language whereas CSS stands for cascading style sheets. HTML provides markup and style to the webpage text. Or we can say it provides a structure to the web page whereas CSS is used to create more interactive web pages. It provides various styling components that define the look of the web page. CSS is independent of HTML and can be used with any XML-based markup language. <!DOCTYPE html> <html> <head> // Header of the web page </head> <body> // Body of the web page </body> </html> DOM − AJAX also has a powerful tool known as DOM(Document Object Model). It is used to interact with and alter the webpage layout and content dynamically. Or we can say that DOM is used to create a logical representation of the elements that are used to markup HTML pages. It is provided by the web browser. It is not a part of JavaScript, but using javaScript we can access the methods and the properties of DOM objects. Using DOM methods and properties we can create or modify HTML pages. <!DOCTYPE html> <html> <head> // Header of the web page </head> <body> <p></p> <script></script> </body> </html> Conclusion So these are the technologies using which AJAX can able to create a dynamic web page. While using these technologies, AJAX has to keep updated its external libraries and frameworks. Now in the next article, we see the Action performed by the AJAX. Print Page Previous Next Advertisements ”;
AJAX – Action
AJAX – Action ”; Previous Next This chapter gives you a clear picture of the exact steps of AJAX operation. Steps of AJAX Operation A client event occurs. An XMLHttpRequest object is created. The XMLHttpRequest object is configured. The XMLHttpRequest object makes an asynchronous request to the Webserver. The Webserver returns the result containing XML document. The XMLHttpRequest object calls the callback() function and processes the result. The HTML DOM is updated. Let us take these steps one by one. A Client Event Occurs A JavaScript function is called as the result of an event. Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to “userid” <input type = “text” size = “20” id = “userid” name = “id” onkeyup = “validateUserId();”>. The XMLHttpRequest Object is Created var ajaxRequest; // The variable that makes Ajax possible! function ajaxFunction() { try { // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”); } catch (e) { try { ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”); } catch (e) { // Something went wrong alert(“Your browser broke!”); return false; } } } } The XMLHttpRequest Object is Configured In this step, we will write a function that will be triggered by the client event and a callback function processRequest() will be registered. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; if (!target) target = document.getElementById(“userid”); var url = “validate?id=” + escape(target.value); ajaxRequest.open(“GET”, url, true); ajaxRequest.send(null); } Making Asynchronous Request to the Webserver Source code is available in the above piece of code. Code written in bold typeface is responsible to make a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; <b>if (!target) target = document.getElementById(“userid”); var url = “validate?id = ” + escape(target.value); ajaxRequest.open(“GET”, url, true); ajaxRequest.send(null);</b> } Assume you enter Zara in the userid box, then in the above request, the URL is set to “validate?id = Zara”. Webserver Returns the Result Containing XML Document You can implement your server-side script in any language, however its logic should be as follows. Get a request from the client. Parse the input from the client. Do required processing. Send the output to the client. If we assume that you are going to write a servlet, then here is the piece of code. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter(“id”); if ((targetId != null) && !accounts.containsKey(targetId.trim())) { response.setContentType(“text/xml”); response.setHeader(“Cache-Control”, “no-cache”); response.getWriter().write(“<valid>true</valid>”); } else { response.setContentType(“text/xml”); response.setHeader(“Cache-Control”, “no-cache”); response.getWriter().write(“<valid>false</valid>”); } } Callback Function processRequest() is Called The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will receive the result from the server and will do the required processing. As in the following example, it sets a variable message on true or false based on the returned value from the Webserver. function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = …; … } The HTML DOM is Updated This is the final step and in this step, your HTML page will be updated. It happens in the following way − JavaScript gets a reference to any element in a page using DOM API. The recommended way to gain a reference to an element is to call. document.getElementById(“userIdMessage”), // where “userIdMessage” is the ID attribute // of an element appearing in the HTML document JavaScript may now be used to modify the element”s attributes; modify the element”s style properties; or add, remove, or modify the child elements. Here is an example − <script type = “text/javascript”> <!– function setMessageUsingDOM(message) { var userMessageElement = document.getElementById(“userIdMessage”); var messageText; if (message == “false”) { userMessageElement.style.color = “red”; messageText = “Invalid User Id”; } else { userMessageElement.style.color = “green”; messageText = “Valid User Id”; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple // replace it otherwise append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } –> </script> <body> <div id = “userIdMessage”><div> </body> If you have understood the above-mentioned seven steps, then you are almost done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail. Print Page Previous Next Advertisements ”;
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 ”;