AJAX – Sending Request ”; Previous Next AJAX applications use XMLHttpRequest objects to initiate or manage data requests sent to the web servers and handle or monitor the data sent by the web servers in a very effective manner. AJAX support the following types of requests − GET request POST request PUT request DELETE request To create a connection and send a request to the web server XMLHttpRequest object provide the following two methods: open() − It is used to create a connection between a web browser and the web server. send() − It is used to send a request to a web server. open() Method The open() method is used to establish an asynchronous connection to the web server. Once the secure connection is established now you are ready to use various properties of XMLHttpRequest, or you can send requests, or handle the responses. Syntax open(method, url, async) Where, the open() method takes three parameters − method − It represents the HTTP method that is used to establish a connection with the web server(Either GET or POST). url − It represents the file URL which will be opened on the web server. Or we can say server(file) location. async − 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. To use the open() method first we create an instance of the XMLHttpRequest object. Then we call the open() method to initialise the request with HTTP GET or POST method and the URL of the server. The GET option is used to retrieve a moderate amount of information from the web server whereas the POST option is used to retrieve a larger amount of information. So both GET and POST options can configure the XMLHttpRequest object to work with the given file. In the open() method, the filename or location or path of an AJAX application can be specified by either using an absolute path or a relative path. Where the absolute path is a path which specifies the exact location of the file, for example − Myrequest.open(“GET”, “http://www.tutorialspoint.com/source.txt”) Here “source.txt” is the name of the file and “http://www.tutorialspoint.com” is the place where the source.txt file is stored. The relative path is used to specify the location of a file according to the location on the web server in relation to the web application file, for example − Myrequest.open(“GET”, “my file.txt”) Syntax Myrequest.send() send() Method The send() method is used to send the request to the server. You can also pass an argument to the send() method. Sending Request To send a request to the server first we need to create an instance of XMLHttpRequest object then we create a callback function which will come into action after getting a response from the web server. Then we use the open() method to establish an asynchronous connection between the web browser and the web server then using send() function we send the request to the server. Example Here in the following code, we are fetching a specified record from the server. To fetch the data from the server we click on the “Click Here” button. So when we click on the “Click Here” button, the showDoc() function is called. Inside the displayDoc() function, first, an object of XMLHttpRequest is created. 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 URL of the server that is “https://jsonplaceholder.typicode.com/todos/3” which fetches a single to-do list whose id = 3 from the JSONPlaceholder API. Then we call send() function to send the request. <!DOCTYPE html> <html> <body> <script> function ShowDoc() { // Creating XMLHttpRequest object var myhttp = new XMLHttpRequest(); // Creating call back function myhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(“example”).innerHTML = this.responseText; } }; // Open the given file myhttp.open(“GET”, “https://jsonplaceholder.typicode.com/todos/3″, true); // Sending the request to the server myhttp.send(); } </script> <div id=”example”> <p>Please click on the button to fetch data</p> <button type=”button” onclick=”ShowDoc()”>Click Here</button> </div> </body> </html> Output After clicking on “Click Here” button we will get the following record from 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 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 example element. Conclusion So this is how we can send requests using XMLHttpRequest. Among all these requests GET and POST are the most commonly used request for fetching and sending data to/from the server. Now in the next article, we will see the type of request supported by AJAX. Print Page Previous Next Advertisements ”;
Category: ajax
AJAX – What is AJAX?
What is AJAX? ”; Previous Next AJAX stands for asynchronous Javascript and XML. AJAX is not a programming language or technology, but it is a combination of multiple web-related technologies like HTML, XHTML, CSS, JavaScript, DOM, XML, XSLT and XMLHttpRequest object. The AJAX model allows web developers to create web applications that are able to dynamically interact with the user. It will also be able to quickly make a background call to web servers to retrieve the required application data. Then update the small portion of the web page without refreshing the whole web page. AJAX applications are much more faster and responsive as compared to traditional web applications. It creates a great balance between the client and the server by allowing them to communicate in the background while the user is working in the foreground. In the AJAX applications, the exchange of data between a web browser and the server is asynchronous means AJAX applications submit requests to the web server without pausing the execution of the application and can also process the requested data whenever it is returned. For example, Facebook uses the AJAX model so whenever we like any post the count of the like button increase instead of refreshing the whole page. Working of AJAX Traditional web applications are created by adding loosely web pages through links in a predefined order. Where the user can move from one page to another page to interact with the different portions of the applications. Also, HTTP requests are used to submit the web server in response to the user action. After receiving the request the web server fulfills the request by returning a new webpage which, then displays on the web browser. This process includes lots of pages refreshing and waiting. AJAX change this whole working model by sharing the minimum amount of data between the web browser and server asynchronously. It speedup up the working of the web applications. It provides a desktop-like feel by passing the data on the web pages or by allowing the data to be displayed inside the existing web application. It will replace loosely integrated web pages with tightly integrated web pages. AJAX application uses the resources very well. It creates an additional layer known as AJAX engine in between the web application and web server due to which we can make background server calls using JavaScript and retrieve the required data, can update the requested portion of a web page without casing full reload of the page. It reduces the page refresh timing and provides a fast and responsive experience to the user. Asynchronous processes reduce the workload of the web server by dividing the work with the client computer. Due to the reduced workload web servers become more responsive and fast. AJAX Technologies The technologies that are used by AJAX are already implemented in all the Morden browsers. So the client does not require any extra module to run the AJAX application.The technologies used by AJAX are − Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications. XML − It is used to exchange data between web server and client. The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server. HTML and CSS − It is used to provide markup and style to the webpage text. DOM − It is used to interact with and alter the webpage layout and content dynamically. Advantages of AJAX The following are the advantages of AJAX − It creates responsive and interactive web applications. It supports the development of patterns and frameworks that decrease the development time. It makes the best use of existing technology and feature instead of using some new technology. It makes an asynchronous call to the web server which means the client doesn”t have to wait for the data to arrive before starting rendering. Disadvantages of AJAX The following are the disadvantages of AJAX − AJAX is fully dependent on Javascript. So if anything happens with javascript in the browser AJAX will not support. The debugging of AJAX applications is difficult. Bookmarking of AJAX-enabled pages required pre-planning. If one request can fail then it can fail the load of the whole webpage. If JavaScript is disabled in your web browser then you are not able to run the AJAX webpage. Conclusion So to create dynamic web pages or applications AJAX is the best choice. It is faster and more responsive and provides asynchronous interaction between the client and server without refreshing the whole page. Now in the next article, we will see the history of AJAX. Print Page Previous Next Advertisements ”;
AJAX – Handling Binary Data
AJAX – Handling Binary Data ”; Previous Next Binary data is data that is in the binary format not in the text format. It includes images, audio, videos, and other file that are not in plain text. We can send and receive binary data in AJAX using an XMLHttpRequest object. While working with binary data in AJAX it is important to set a proper content type and response type headers. Hence for setting the header, we use the “Content-Type” header, here we set the proper MIME type to send binary data and set the “responseType” property to “arraybuffer” or “blob” which indicates that binary data is received. Sending Binary Data To send binary data we use send() method of XMLHttpRequest which can easily transmit binary data using ArrayBuffer, Blob or File object. Example In the following program, we create a program which will receive binary data from the server. So when we click on the button getBinaryData() function trigger. It uses an XMLHttpRequest object to get the data using the GET method from the given URL. In this function, we set the responseType property to arraybuffer which tells the browser that we have to only accept binary data in the response. When the request is completed an onload() function is called and inside this function, we check the status of the request if the response is successful, then the response is accessed as arraybuffer. Then convert arraybuffer into Uint8array using Unit8Array() function. It accesses the individual bytes of the binary data. After that, we will display the data on the HTML page. <!DOCTYPE html> <html> <body> <script> function getBinaryData() { // Creating XMLHttpRequest object var myhttp = new XMLHttpRequest(); // Getting binary data myhttp.open(“GET”, “https://jsonplaceholder.typicode.com/posts”, true); // Set responseType to arraybuffer. myhttp.responseType = “arraybuffer”; // Creating call back function myhttp.onload = (event) => { // IF the request is successful if (myhttp.status === 200){ var arraybuffer = myhttp.response; // Convert the arraybuffer into array var data = new Uint8Array(arraybuffer); // Display the binary data document.getElementById(“example”).innerHTML = data; console.log(“Binary data Received”); }else{ console.log(“Found error”); } }; // Sending the request to the server myhttp.send(); } </script> <div id=”example”> <p>AJAX Example</p> <button type=”button” onclick=”getBinaryData()”>Click Here</button> </div> </body> </html> Output Conclusion So this is how we can handle binary data. To handle binary data we need to convert binary data to an appropriate data format. We can also send binary data in the file, string, ArrayBuffer, and Blob. Now in the next article, we will learn how to submit forms using 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 ”;