Fetch API – Send JSON Data

Fetch API – Send JSON Data ”; Previous Next Fetch API is used to send or receive data asynchronously without refreshing the web page. In the Fetch API, we can send data in various formats like JSON, URL-encoded form, Text, FormData, Blob or ArrayBuffer. Among all these forms JSON (JavaScript Object Notation) data is the most commonly used format to send data using Fetch because it is simple, lightweight, and compatible with most of the programming languages. JSON data is generally created in the following format − Const JSONData = { name: “Monika”, Id: 293, Age: 32, City: “Pune” }; Where name, id, Age, and City are the properties and Monika, 293, 32, and Pune are their values. Fetch API generally sends JSON data as a payload in the request body or can be received in the response body. And the data is serialized as a string because it is easy to transmit data from one system to another. While working with JSON data, Fetch API perform two main operations on JSON data − Serializing − While sending JSON data in a request we need to convert the value into JSON string format using the “JSON.stringify()” function. This function takes an object or value as an input parameter and returns a string which represents JSON format. Due to serializing data, we can easily transmit data over the network. Syntax JSON.stringify() Parsing − Parsing is a process in which we convert the JSON string received in the response back into the JavaScript object or value. This parsing of JSON data can be done by using the response.json() function. This function takes the response object as an argument and returns a promise which is resolved in the parsed JSON data or JavaScript object. Syntax response.json() Send JSON Data To send JSON data Fetch API uses the following ways − Using fetch() function Using the fetch() function with async/await Using request object Method 1 − Using the fetch() function We can send data using the fetch() function. In this function, we create JSON data in the body parameter and use the POST request method to send data on the specified URL. Example In the following program, we will send JSON data using the fetch() function. The fetch() function is used to create a request. The request contains the POST method which tells us that we want to send data, a body which contains JSON data which is converted into a string using stringify() and the header which specifies that we are sending JSON data. After sending the request the server returns a promise which will resolve to a Response object and using .json() we parse the JSON data and display the result in the console log. If we encounter an error, then the error is handled by the catch block. <!DOCTYPE html> <html> <body> <script> // Sending JSON data using a POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request method: “POST”, // Add a body which contains JSON data body: JSON.stringify({ id: 290, title: “Today is the rainy day”, }), // Setting headers headers:{“Content-type”: “application/json; charset=UTF-8”} }) // Converting response to JSON .then(response => response.json()) .then(myData => { console.log(“Data Sent Successfully”); // Display output in HTML page document.getElementById(“sendData”).innerHTML = JSON.stringify(myData); }) .catch(err=>{ console.error(“We get an error:”, err); }); </script> <h2>Sent Data</h2> <div> <!– Displaying data–> <p id = “sendData”></p> </div> </body> </html> Output Method 2 − Using fetch() function with async/await We can also send JSON data using the fetch() function with async/await. Async/await allows you to create an asynchronous program which behaves more like a synchronous program which makes it easier to learn and understand. Example In the following program, we will send JSON data using the fetch() function with async/await. So for that, we create an async function. In the function, we use try block which uses the fetch() function along with the resource URL, the POST request method, header, and body(JSON data in string format) parameters to send JSON data to the given URL. It also uses await keyword with the fetch() function which is used to wait for the response from the server. If the response is a success, then we parse the response return by the server using the .json() function. If the status code of the response contains an unsuccessful code the else block runs. If we encounter an error during the fetch operation, then that error is handled by the catch block. <!DOCTYPE html> <html> <body> <script> async function sendingJSONData(){ try{ const retrunResponse = await fetch(“https://jsonplaceholder.typicode.com/todos”, { // Setting POST request to send data method: “POST”, // Add body which contains JSON data body: JSON.stringify({ id: 290, title: “Today is the rainy day”, }), // Setting headers headers:{“Content-type”: “application/json; charset=UTF-8”} }); if (retrunResponse.ok){ // Handling response const returnData = await retrunResponse.json(); console.log(“Data send Successfully”); // Display output in HTML page document.getElementById(“sendData”).innerHTML = JSON.stringify(returnData); } else { console.log(“We found error”, retrunResponse.status); } } catch(err) { // Handling error if occur console.error(“Error is:”, err) } } sendingJSONData(); </script> <h2>Sent Data</h2> <div> <!– Displaying data–> <p id = “sendData”></p> </div> </body> </html> Output Method 3 − Using request object We can also send JSON data using a request object. It is an alternative to the fetch() function to send requests to the server. The request object also uses the POST method to send JSON data on the specified URL. The request object is created by using the Request() constructor of the Request interface. The request object provides more flexibility in creating or configuring the request before sending it by the fetch() function. It also allows us to add additional options like header, caching, request method, etc. Example In the following program, we will send JSON data using a request

AJAX – Useful Resources

Ajax – Useful Resources ”; Previous Next The following resources contain additional information on Ajax. Please use them to get more in-depth knowledge on this topic. Useful Video Courses JQuery Masterclass Course: JavaScript And AJAX Coding Bible 73 Lectures 4.5 hours Frahaan Hussain More Detail AJAX API JSON Connect to JSON data using AJAX webpage Most Popular 21 Lectures 1 hours Laurence Svekis More Detail The Complete Web Development Course 201 Lectures 18.5 hours Metla Sudha Sekhar More Detail Learn XML-AJAX – A Course For Beginners 30 Lectures 2 hours YouAccel More Detail Create a Members Only Blog using PHP, MySQL & AJAX 21 Lectures 1.5 hours YouAccel More Detail Fundamentals of Ajax, jQuery and JSON Online Course 18 Lectures 2.5 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;

AJAX – FormData Object

AJAX – FormData Object ”; Previous Next In AJAX, the FormData object allows you to create a set of key-value pairs which represent the form fields and their values, which can be sent using XMLHttpRequest. It is mainly used in sending form data but can also be used independently to send data. The data transmitted by the FormData object is in the same format as the data sent by the form”s submit method. To create a new FormData object AJAX provide FormData() constructor. Syntax const objectName = new FormData() Or const objectName = new FormData(form) Or const objectName = new FormData(form, mSubmit) Where the FormData() can be used with or without parameters. The optional parameters used by the FormData() constructor are − form − It represents an HTML <form> element. If the FormData object has this parameter, then the object will be populated with the current key-value pair of the form using the name property of each element for the key and their submitted value. It also encodes the input content of the file. mSubmit − It represents the submit button the form. If mSubmit has a name attribute or an <input type = “image>, then its content will include in the FormData object. If the specified mSubmit is not a button, then it will throw a TypeError exception. If the mSubmit is not a member of the given form, then it will throw NotFoundError. Methods FormData object supports the following methods − Sr.No. Method Name & Description 1 FormData.append() This method is used to append a new value into an existing key. Or can add a new key if it is not present. 2 FormData.delete() This method is used to delete key-value pairs. 3 FormData.entries() This method returns an iterator that iterates through key-value pair. 4 FormData.get() This method returns the first value related to the given key from the FormData object. 5 FormData.getAll() This method is used to return an array of all the values related to the given key in the FormData object. 6 FormData.has() This method checks whether a FormData object contains the specified key or not. 7 FormData.keys() This method returns an iterator which iterates through all the keys of the key-value pairs present in the FormData object. 8 FormData.set() This method sets a new value for the existing key in the FormData object. Or can add new key/value if not exists. 9 FormData.values() This method returns an iterator which iterates through all the values present in the FormData object. Creating FormData Object To create and use FormData Object without using HTML form follow the following steps − Step 1 − Create an XMLHttpRequest object using XMLHttpRequest () constructor − var zhttp = new XMLHttpRequest(); Step 2 − Create a FormData object using FormData constructor − const myForm = new FormData() Step 3 − Use append() method to add key and value pairs − myForm.append(“KeyName”, “keyValue”) Step 4 − Create a call back function to handle response zhttp.onreadystatechange = function() { // Body } Step 5 − Now we use open() function. Inside open() function we pass a POST request along with the server URL we have to post our form data. zhttp.open(“POST”, url, async) Step 6 − So finally we use send() function to send requests to the server along with the FormData object. zhttp.send(myForm); Now let”s discuss this with the help of the example − Example 1 <!DOCTYPE html> <html> <body> <script> function dataDoc() { // Creating XMLHttpRequest object var zhttp = new XMLHttpRequest(); // Creating FormData object const myForm = new FormData(); // Assigning the form data object with key/value pair myForm.append(“title”, “AJAX Tutorial”) myForm.append(“UserId”, “232”) myForm.append(“Body”, “It is for web development”) myForm.append(“Age”, “33”) // Creating call back function to handle the response zhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 201) { document.getElementById(“example”).innerHTML = this.responseText; console.log(“Form Data Posted Successfully”) } }; // Specify the method as POST, URL, and set async to true zhttp.open(“POST”, “https://jsonplaceholder.typicode.com/todos”, true); // Sending the request to the server zhttp.send(myForm); } </script> <h2>Sending Form Data</h2> <button type=”button” onclick=”dataDoc()”>Submit</button> <div id=”example”></div> </body> </html> Output So when the user clicks on the “Submit” button dataDoc() function is called. Then dataDoc() function first creates a new XHR object and a new FormData object. Then add new key-value pairs in the FormData object using the append() method. Next, it set up a call-back function which handles the response from the server. This function is triggered when the value of the readyState property = 4 and the value of the Status property = 201. Finally, it calls the open() method and initialises it with the HTTP POST method with the URL of the server and at last it calls send() method to send the FormData request to the server. So when the response comes from the server the call-back function displays the result and prints the “Form Data Posted Successfully” message on the console log. Example 2 <!DOCTYPE html> <html> <body> <script> function sendFormData() { // Creating XMLHttpRequest object var zhttp = new XMLHttpRequest(); // Creating FormData object const myForm = new FormData(); // Assigning the form data with key/value pair myForm.append(“title”, document.querySelector(”#Utitle”).value) myForm.append(“UserId”, document.querySelector(”#UId”).value) myForm.append(“Body”, document.querySelector(”#Ubody”).value) myForm.append(“Age”, document.querySelector(”#Uage”).value) // Creating call back function to handle the response zhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 201) { document.getElementById(“example”).innerHTML = this.responseText; console.log(“Form Data Posted Successfully”) } }; // Post/Add form data on the server zhttp.open(“POST”, “https://jsonplaceholder.typicode.com/todos”, true);

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 & Description 1 new XMLHttpRequest() It is used to create an XMLHttpRequest() object 2 abort() It is used to cancel the current request. 3 getAllResponseHeaders() It is used to get the header information 4 getResponseHeader() It is used to get the specific header information 5 open(method, url, async, user, psw) 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 6 send() It is used to send requests to the web server. It is generally used for GET requests. 7 send(string) It is used to send requests to the server. It is generally used for POST requests. 8 setRequestHeader() It is used to add key/value pair to the header. XMLHttpRequest Object Properties XMLHttpRequest object has the following properties − Sr.No. Property & 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 a web browser and the web server. So now in the next article, we will learn how to send a request using an XMLHttpRequest object. Print Page Previous Next Advertisements ”;

Stream API – Writeable Streams

Stream API – Writeable Streams ”; Previous Next Writable Streams are those streams in which we can write data. They are generally represented in JavaScript by WritableStrem object. It creates an abstraction over the underlying sink. The underlying sink is a lower-level input/output sink where the raw data is written. In the writable stream, a writer writes the data. It writes one chunk at a time, where a chunk is a piece of data. Also, you are allowed to use any code to produce the chunk for writing, and the writer and the related code together are known as the producer. On a single stream, only one writer is allowed to write data. At that time the stream is locked for that specified writer, no other writer is allowed to write. If you want another writer to write, then you have to terminate the first writer after that the other writer is allowed to write. Every writer has their own controller which controls the stream. Also, the writable stream has an internal queue just like a readable stream. It also keeps track of chunks that are written but not processed by the underlying sink. WritableStream Interfaces Stream API supports three types of writable stream interfaces − WritableStream Interface WritableStreamDefaultWriter Interface WritableStreamDefaultController Interface WritableStream Interface The WritableStream Interface is used to write streaming data to the sink. Its object comes with in-built backpressure and queuing. Constructor To create a WritableStream object, the WritableStream interface provides a WritableStream() constructor. Syntax const newWrite = new WritableStream(UnderlyingSink) Or const newWrite = new WritableStream(UnderlyingSink, QueuingStrategy) The WritableStream() constructor has the following optional parameters − UnderlyingSink − This object provides various methods and properties that show the behaviour of the write stream instance. It takes four parameters: start(controller), write(chunk, controller), close(controller), and abort(reason). QueuingStrategy − This object is used to define the queuing strategy for the write streams. It takes two parameters: highWaterMark, and size(chunk). Instance Properties The properties provided by the WritableStream interface are read-only properties. So the properties provided by WritableStream are − Sr.No. Property & Description 1 WritableStream.locked This property is used to check whether the WritableStream is locked to the writer or not. Methods The following are the commonly used method of the WritableStream interface − Sr.No. Property & Description 1 WritableStream.close() This method is used to close the stream. 2 WritableStream.abort() This method is used to abort the stream. 3 WritableStream.getWriter() This method is used to get a new object of WriteableStreamDefaultWriter and will lock the stream to that instance. When the stream is locked no other writer can able to get until the current object is released. WritableStreamDefaultWriter Interface The WritableStreamDefaultWriter interface is used to represent a default writer which will write chunks of data to the stream. Constructor To create a WritableStreamDefaultWriter object, the WritableStreamDefaultWriter interface provides a WritableStreamDefaultWriter() constructor. Syntax const newWrite = new WritableStreamDefaultWriter(myStream) This constructor contains only one parameter which is myStream. It will read ReadableStream. Instance Properties The properties provided by the WritableStreamDefaultWriter interface are read-only properties. So the properties provided by WritableStreamDefaultWriter are − Sr.No. Property & Description 1 WritableStreamDefaultWriter.closed This property returns a promise which will resolve if the stream is closed or rejected due to some error. It allows you to create a program which will respond at the end of the stream process. 2 WritableStreamDefaultWriter.desiredSize This property is used to get the desired size that will fulfil the stream internal queue. 3 WritableStreamDefaultWriter.ready This property returns a promise which will resolve when the desired size of the stream internal queue transition from negative to positive. Methods The following are the commonly used method of the WritableStreamDefaultWriter interface − Sr.No. Method & Description 1 WritableStreamDefaultWriter.abort() This method is used to abort the stream. 2 WritableStreamDefaultWriter.close() This method is used to close the writable stream. 3 WritableStreamDefaultWriter.releaseLock() This method is used to remove the lock of the writer on the corresponding stream. 4 WritableStreamDefaultWriter.write() This method is used to write a passed piece of data to a WritableStream and its underlying sink. It will return a promise which resolves to determine whether the write operation is a failure or success. WritableStreamDefaultController Interface The WritableStreamDefaultController interface represents a controller which allows us to control the WritableStream State. It does not provide any controller and the instance is created automatically while constructing WritableStream. Instance Properties The properties provided by the WritableStreamDefaultController interface are read-only properties. So the properties provided by WritableStreamDefaultController are − Sr.No. Property & Description 1 WritableStreamDefaultController.signal This property will return an AbortSignal related to the specified controller. Methods The following are the commonly used method of the WritableStreamDefaultController interface − Sr.No. Method & Description 1 WritableStreamDefaultController.error() This method will cause any future interaction with the related write stream to the error. Example – Creating Writable Stream In the following program, we create a custom writable stream. So to create a writable stream Stream API provide WritableStream() constructor with the write(), cancel() and abort() functions. The write() function is used to log the received chunks, the cancel() function is used to handle when a stream is cancelled, and the abort() function is used to handle when the stream is aborted. Now we create a

AJAX – Status Codes

AJAX – Status Codes ”; Previous Next In AJAX, XMLHttpRequest supports various properties and methods to perform different types of operations. Among these properties and methods status property/attribute is a status code that specifies the overall status of the data request sent by the XMLHttpRequest object. Or we can say that the status code is a three-digit number which represent the result of the request sent by the XMLHttpRequest object like the request was successful, run into an error, or redirected, etc. So the syntax of the status property is − Format if(XMLHttpRequestObjectName.status == 200){ // Body } Here we can access a status property or attribute using the XMLHttpRequest object. If the status code is equal to 200, then the code inside the body will execute. Status Codes The status codes that HTTP status returned are as follows − Successful Status Message Description 200 OK If the request is OK. 201 Created When the request is complete and a new resource is created. 202 Accepted When the request is accepted by the server. 204 No Content When there is no data in the response body. 205 Reset Content For additional inputs the browser clears the form used for transaction. 206 Partial Content When the server returns the partial data of the specified size. Redirection Status Message Description 300 Multiple Choices It is used to represent a link list. So that user can select any one link and go to that location. It allows only five locations. 301 Moved Permanently When the requested page is moved to the new URL. 302 Found When the requested page is found in a different URL. 304 Not modified URL is not modified. Client Error Status Message Description 400 Bad Request The server cannot fulfil the request because the request was malformed or has invalid syntax. 401 Unauthorised The request needs authentication and the user does not provide valid credentials. 403 Forbidden The server understood the request but does not fulfil it. 404 Not Found The requested page is not found. 405 Method Not Allowed The method through which the request is made is not supported by the page. 406 Not Acceptable The response generated by the server cannot be accepted by the client. 408 Request Timeout Server timeout 409 Conflict The request does not fulfil due to a conflict in the request. 410 Gone The requested page is not available. 417 Exception Failed The server does not match the requirement of the Expect request header field. Server Error Status Message Description 500 Internal Server Error When the server encounter error while processing the request 501 Not Implemented When the server does not recognise the request method or lacks of ability to fulfil the request 502 Bad Gateway When the server acts like a gateway and recovers an invalid response from another server(upstream) 503 Service Unavailable When the server is not available or down 504 Gateway Timeout When the server acts like a gateway and does not receive a response from the other server(upstream) on time. 505 HTTP Version Not Supported When the server does not support the version of the HTTP protocol. 511 Network Authentication Required When the client needs to authenticate to gain access to the network. Flow Chart In the below code, we retrieve the data from the server. So we create a function named as showDoc(). Now we call this function by clicking on the “Click Here” button. This function will create a new XHR object using XMLHttpRequest() constructor. Then it creates a call-back function which will handle the request. Then it calls the open() function of the XHR object to initialise the request with HTTP GET method and the URL of the server. Finally, it calls send() function to send the request to the server. So when the server responds to the request the “onreadystatechange” property calls the callback function with the current state of XMLHttpRequest object. If the status is 200 then that means the request is successful, so it displays the result on the screen and writes a message in the console log. If the status is 404, then that means the server encountered an error. So we got an error message in the console log. Example <!DOCTYPE html> <html> <body> <script> function ShowDoc() { // Creating XMLHttpRequest object var myhttp = new XMLHttpRequest(); // Creating call back function myhttp.onreadystatechange = function() { // Checking the status of the response // This will proceed when the response is successful if (this.status == 200){ console.log(“Found the requested data”) document.getElementById(“example”).innerHTML = this.responseText; } // This will proceed when the error is found else if(this.status == 404){ console.log(“Found error”); } }; // Open the given file myhttp.open(“GET”, “https://jsonplaceholder.typicode.com/todos/3″, true); // Sending the request to the server myhttp.send(); } </script> <p>Please click on the button to fetch data</p> <button type=”button” onclick=”ShowDoc()”>Click Here</button> <div id=”example”></div> </body> </html> Output

AJAX – Monitoring Progress

AJAX – Monitoring Progress ”; Previous Next AJAX provides a special feature named Monitoring Progress. Using this feature we can able to track the progress of the asynchronous request made by the AJAX from the web browser to the web server. Or we can say that using a progress monitor we can also monitor how much amount of data is uploaded or downloaded from the server to the user. With the help of monitoring progress, we can send feedback to the user which contains the following points − Data Transfer Progress − We can monitor the progress of the data transferred from the server to the client. Or we can also track how much data is transferred or received as compared to the total size of the given file. Request Status − Wan can also monitor the overall status (like whether the request is still in progress or it is complete or pending) of the request we made. It helps the programmer to provide proper feedback to the user of the current request. Error Handling − Apart from tracking the current status it is also important to handle if any error occurs while requesting data like server-side errors, network issues, etc. So using error handling we can easily send a notification to the user so that he/she can take proper action to the occurred error. How to Monitor Progress To monitor the progress of the AJAX request we can use the following methods − Using onprogress event − To monitor the progress of the request we can define an “onprogress” event which triggers periodically while the data transfer is processed. It is generally used to monitor the progress of file downloads or large data/file transfers. It monitors the progress of the information like how much data is loaded, the total size of the transferred data, etc. Example In the following program, we will monitor the current status of the request with the help of the onprogress event. Here we create a Javascript function named as displayStatus() which shows the states of how much data is being transferred. This function makes an AJAX request to send data to the given URL. So it uses an XMLHttpRequest object to create a request and then defines a callback function to handle the response provided by the server. Inside the callback function. The onprogress event checks the current progress of the transferred data. Inside the onprogress event handler, we can check if the progress data is computable to avoid dividing zero errors. If it is computable, then we can calculate the percentage of data transferred to the server. <script> function displayStatus() { // Creating XMLHttpRequest object var myObj = new XMLHttpRequest(); // Creating call back function // Here onprogress return the percentage of transferred data myObj.onprogress = function(myEvent) { if (myEvent.lengthComputable){ var dataTarnsferPercentage = (myEvent.loaded/myEvent.total)*100; console.log(“Current progress of the data transfer:”, dataTarnsferPercentage); } }; // Open the given file myObj.open(“GET”, “https://jsonplaceholder.typicode.com/todos”, true); // Sending the request to the server myObj.send(); } </script> Using onreadystatechange event − We can monitor the progress of the request by creating an onreadystatechnage event. This event triggers whenever the readyState property of the XMLHttpRequest changes. The readyState property returns the current state of the request. Example In the following program, we will monitor the current status of the request with the help of the onreadystatechange event. Here we create a Javascript function named as displayStatus() which shows the states of the current status of the request. This function makes an AJAX request to retrieve data from the given URL. So it uses an XMLHttpRequest object to create a request and then defines a callback function to handle the response provided by the server. Inside the callback function. The onreadystatechange event checks the current status of the request with the help of the readyState property. If the readyState is XMLHttpRequest.DONE, that means the request is completed and print “Request is completed”. Otherwise print “Request is in-progress”. <script> function displayStatus() { // Creating XMLHttpRequest object var myObj = new XMLHttpRequest(); // Creating call back function // Here onreadystatechange return the current state of the resuest myObj.onreadystatechange = function() { if (this.readyState == XMLHttpRequest.DONE){ console.log(“Request is completed”) }else{ console.log(“Request is in-progress”) } }; // Open the given file myObj.open(“GET”, “https://jsonplaceholder.typicode.com/todos”, true); // Sending the request to the server myObj.send(); } </script> Conclusion So this is how we can monitor the progress of the requests. So that we can easily track down how much data is being transferred, how much data is handled successfully, errors, etc. Now in the next article, we will see the status codes supported by the AJAX. Print Page Previous Next Advertisements ”;

AJAX – Applications

AJAX – Applications ”; Previous Next AJAX is the commonly used web technology to send and receive data to and from the web server asynchronously without reloading all the components of the web page. It is effortless to understand and use because it doesn”t use any new technology instead it is a combination of existing web technologies like JavaScript, XML, HTML, etc. It makes web applications more responsive and interactive so that they can fetch and show data in real-time without refreshing the full page. Due to its tremendous functionality, it is used by almost all web application creators including small or large firms. AJAX is generally used by almost all the applications present on the internet. Some of the popular applications are − Google Maps − It is a great example of an AJAX application. It uses AJAX to dynamically update the maps and show only the requested data without reloading the whole page. Facebook − It is also a good example of an AJAX application. It uses AJAX to update the feeds, notifications, news, and other features. Ajax is also used for update the Facebook content of the web page according to the action of the user. Gmail − Gmail also uses AJAX to provide a seamless and interactive environment to the user. With the help of AJAX Gmail can update the inbox, delete emails, or mark emails as read without reloading the page. Twitter − Twitter is also one of the great examples of an AJAX application. Using AJAX provide a real-time environment to the user. Whenever a new tweet is posted it will add to the timeline without refreshing the whole page. The same goes for the notification. Online shopping websites − AJAX is also used by online shopping websites to show product details and their real-time prices without requiring users to navigate to a new webpage. Google − Google also uses AJAX for its auto-complete feature. The auto-complete feature comes in the picture when the user enters something in the Google search bar and then this feature provides real-time suggestions in the drop-down list without reloading the original web page. This feature is used in various forms also. Chats and instant messages − Nowadays most websites use customer support chat facilities through which they can communicate with their customers without reloading the entire webpage. AJAX also achieves this facility. Form submission and validations − Various websites use AJAX for the submission and validation of forms. It provides an auto-filling feature in some fields of the form and can give suggestions(like autocomplete feature) for the possible entries for the specified field. AJAX is also used to validate the credentials of the user. Voting and rating systems − Various websites use rating and voting systems, allowing users to customise the data according to the votes and ratings. Also, users can allow to vote or rate the content present on the given website and then the site updates its content accordingly. Such type of sites uses AJAX to manage user votes and rating. Conclusion So overall AJAX is a very powerful technique which allows web developers to create interactive and dynamic web applications. Using this technique application can communicate with the server asynchronously without refreshing the whole page for each request. Dynamic applications provide a smooth browser experience to their users. Now in the next article, we will see database operations. Print Page Previous Next Advertisements ”;

Fetch API – Send POST Requests

Fetch API – Send POST Requests ”; Previous Next Just like XMLHttpRequest, Fetch API also provides a JavaScript interface to manage requests and responses to and from the web server asynchronously. It provides a fetch() method to fetch resources or send the requests to the server asynchronously without reloading the web page. With the help of the fetch() method, we can perform various requests like POST, GET, PUT, and DELETE. So in this article, we will learn how to send POST requests with the help of Fetch API. Send POST Request Fetch API also support POST request. The POST request is an HTTP request which is used to send data or form to the given resource or the web server. In Fetch API, we can use POST requests by specifying the additional parameters like method, body headers, etc. Syntax fetch(URL, { method: “POST”, body: {//JSON Data}, headers:{“content-type”: “application/json; charset=UTF-8”} }) .then(info =>{ // Code }) .catch(error =>{ // catch error }); Here the fetch() function contains the following parameters − URL − It represents the resource which we want to fetch. method − It is an optional parameter. It is used to represent the request like, GET, POST, DELETE, and PUT. body − It is also an optional parameter. You can use this parameter when you want to add a body to your request. header − It is also an optional parameter. It is used to specify the header. Example In the following program, we will send a JSON document to the given URL. So for that, we define a fetch() function along with a URL, a POST request, a body(that is JSON document) and a header. So when the fetch() function executes it sends the given body to the specified URL and converts response data into JSON format using the response.json() function. After that, we will display the response. <!DOCTYPE html> <html> <body> <script> // Retrieving data from the URL using POST request fetch(“https://jsonplaceholder.typicode.com/todos”, { // Adding POST request method: “POST”, // Adding body which we want to send body: JSON.stringify({ id: 32, title: “Hello! How are you?”, }), // Adding headers headers:{“Content-type”: “application/json; charset=UTF-8”} }) // Converting received information into JSON .then(response => response.json()) .then(myData => { // Display the retrieve Data console.log(“Data Sent Successfully”); // Display output document.getElementById(“manager”).innerHTML = myData; }); </script> <h2>Display Data</h2> <div> <!– Displaying retrevie data–> <table id = “manager”></table> </div> </body> </html> Output Conclusion So this is how we can send the POST request using Fetch API. Using this request we can easily send data to the specified URL or server. Also using the fetch() function you can modify your request according to your requirements. Now in the next article, we will learn how to send a PUT request. Print Page Previous Next Advertisements ”;

Fetch API – Send GET Requests

Fetch API – Send GET Requests ”; Previous Next Fetch API provides an interface to manage requests and responses to and from the web server asynchronously. It provides a fetch() method to fetch resources or send the requests to the server asynchronously without refreshing the web page. Using the fetch() method we can perform various requests like POST, GET, PUT, and DELETE. In this article, we will learn how to send GET requests using Fetch API. Send GET Request The GET request is an HTTP request used to retrieve data from the given resource or the web server. In Fetch API, we can use GET requests either by specifying the method type in the fetch() function or without specifying any method type in the fetch() function. Syntax fetch(URL, {method: “GET”}) .then(info =>{ // Code }) .catch(error =>{ // catch error }); Here in the fetch() function, we specify the GET request in the method type. Or fetch(URL) .then(info =>{ // Code }) .catch(error =>{ // catch error }); Here, in the fetch() function, we do not specify any method type because by default fetch() function uses a GET request. Example In the following program, we will retrieve id and titles from the given URL and display them in the table. So for that, we define a fetch() function with a URL from where we retrieve data and a GET request. This function will retrieve data from the given URL and then convert the data into JSON format using the response.json() function. After that, we will display the retrieved data that is id and title in the table. <!DOCTYPE html> <html> <body> <script> // GET request using fetch()function fetch(“https://jsonplaceholder.typicode.com/todos”, { // Method Type method: “GET”}) // Converting received data to JSON .then(response => response.json()) .then(myData => { // Create a variable to store data let item = `<tr><th>Id</th><th>Title</th></tr>`; // Iterate through each entry and add them to the table myData.forEach(users => { item += `<tr> <td>${users.id} </td> <td>${users.title}</td> </tr>`; }); // Display output document.getElementById(“manager”).innerHTML = item; }); </script> <h2>Display Data</h2> <div> <!– Displaying retrevie data–> <table id = “manager”></table> </div> </body> </html> Output Conclusion So this is how we can send the GET request using Fetch API so that we can request a specific resource or document from the given URL. Using the fetch() function we can also customise the GET request according to our requirements. Now in the next article, we will learn how to send a POST request. Print Page Previous Next Advertisements ”;