Fetch API – Browser Compatibility

Fetch API – Browser Compatibility ”; Previous Next Fetch API provides a modern JavaScript interface that is used to send requests to the server and handle the response from the server asynchronously. It is more powerful and flexible as compared to the XMLHttpRequest object. Compatible Browsers The Fetch API is supported by almost all modern web browsers. The following list shows the browsers named and their versions that support Fetch API − Browser Name Versions Chrome 42-117 Edge 14-114 Firefox 39-117 Safari 10.1-16.6 Opera 29-100 Chrome Android 101 Firefox for Android 111 Opera Android 70 Safari on IOS 10.3-16.6 Samsung Internet 4-19 Compatibility Check The browser compatibility can change over time due to new versions. So, it is a good practice to check the current browser compatibility of Fetch API. The following are the key points that are used to check the compatibility of the web browser − Versions of web browser − While using Fetch API, please make sure that you are fully aware of what version of the browser you will require for using Fetch API because different versions of web browsers have their level of support for Fetch API. Support of Fetch API − While using a web browser always verifies that the web browser you are using supports Fetch API. Although almost all modern web browsers support Fetch API, in case you are using an older browser then it will not support Fetch API. Feature Detection − It is a technique which is used to check if the current web browser supports Fetch API or not. It creates a code which checks the presence of the specified Fetch API method or property or it can also provide alternate functionality if they are not supported by the current web browser. Cross-Origin Requests − While using Fetch API always check if the current browser supports cross-origin requests. Cross-origin resource sharing (CORS)policy can put a direct effect on making requests to different domains. So always make sure that the browser you are using must contain necessary CORS headers and can handle cross-origin requests properly. HTTPS requirement − Some web browsers apply some restrictions on creating Fetch API requests from HTTP origin to HTTPS origin. So always check such types of restrictions and make the necessary changes in the application so that it will meet all the security requirements. Handling errors − The browser you are using must handle the error and HTTP status codes correctly. Make sure that the web browser provides the necessary error information for proper error handling. So using these points we can check the compatibility of the web browser by using Fetch API. Conclusion So this is how we can check the browser compatibility. Fetch API is generally supported by all modern browsers. It does not support older web browsers. So if you are working with old web browsers, then you have to use XMLHttpRequest. Now in the next article, we will learn about Fetch API Headers. Print Page Previous Next Advertisements ”;

AJAX – Browser Support

AJAX – Browser Support ”; Previous Next All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX. Mozilla Firefox 1.0 and above. Netscape version 7.1 and above. Apple Safari 1.2 and above. Microsoft Internet Explorer 5 and above. Konqueror. Opera 7.6 and above. When you write your next application, do consider the browsers that do not support AJAX. NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object − XMLHttpRequest object. Writing Browser Specific Code The simplest way to make your source code compatible with a browser is to use try…catch blocks in your JavaScript. Example <html> <body> <script language = “javascript” type = “text/javascript”> <!– //Browser Support Code function ajaxFunction() { var ajaxRequest; // The variable that makes Ajax possible! 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; } } } } //–> </script> <form name = ”myForm”> Name: <input type = ”text” name = ”username” /> <br /> Time: <input type = ”text” name = ”time” /> </form> </body> </html> Output In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt − ajaxRequest = new XMLHttpRequest(); It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with − ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”); ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”); If it doesn”t work, then we can use a very outdated browser that doesn”t support XMLHttpRequest, which also means it doesn”t support AJAX. Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter. Print Page Previous Next Advertisements ”;

AJAX – Submitting Forms

AJAX – Submitting Forms ”; Previous Next AJAX is the most popular web technique which is used by almost all web developers to create dynamic web applications. It uses web browsers” in-built XMLHttpRequest object to send and receive data asynchronously to or from the web server in the background without refreshing or affecting the web page. We can also use AJAX to submit forms very easily. So to submit the form using AJAX we need to follow the following steps − Step 1 − Create an XMLHttpRequest object using XMLHttpRequest () constructor − var zhttp = new XMLHttpRequest(); Step 2 − Create a variable(also known as form element) which contains all the keys and value pairs present in the form with the help of the document.querySelector() method. const FormElement = document.querySelector(“mForm”) Here if you have multiple forms, then you can define forms with their ids. Step 3 − FormData object using FormData constructor and pass the above created FormElement into it. It means that the FormData object is initialised with the key-value pairs. const myForm = new FormData(FormElement) Step 4 − Create a call-back function which will be executed when the server responds to the request. This function is defined inside the onreadystatechange property of the XHR object. zhttp.onreadystatechange = function() { // Body } Here the responseText property will return the response of the server as a JavaScript string which we will further use in our web page to display the message. document.getElementById(“responseElement”).innerHTML = this.responseText; Step 5 − Now we use the open() function. Inside the open() function we pass a POST request along with the URL to which we have to post our form data. zhttp.open(“POST”, url, async) Step 6 − Finally we use send() function to send a request to the server along with the FormData object. zhttp.send(myForm); So the complete example is as follows − Example Here in the above code, we create a simple HTML form to collect data from the user and then submit the form data using JavaScript with XMLHttpRequest. So when the user clicks on the “Submit Record” button sendFormData() function is called. The sendFormData() function first creates a new XHR object. Then create a form element which stores all the key-value pairs from the HTML form. Then it is a new FormData object and passes the form element into the object. 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 shows the result and prints the message on the console log. <!DOCTYPE html> <html> <body> <script> function sendFormData() { // Creating XMLHttpRequest object var zhttp = new XMLHttpRequest(); const mFormEle = document.querySelector(“#mForm”) // Creating FormData object const myForm = new FormData(mFormEle); // 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); // Sending the request to the server zhttp.send(new FormData(mFormEle)); } </script> <!–Creating simple form–> <form id = “mForm”> <h2>Enter the requested 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> <label for=”Uage”>Age</label> <input id=”Uage” type=”number” name=”age”><br> <button type=”button” onclick=”sendFormData()”>Submit Record</button> </form> <div id=”example”></div> </body> </html> Output Conclusion So this is how AJAX submit form using XMLHttpRequest. It is the most commonly used feature of AJAX. Now in the next article, we will see how AJAX upload files to the server. Print Page Previous Next Advertisements ”;

AJAX – Send JSON Data

AJAX – Send JSON Data ”; Previous Next AJAX is asynchronous Javascript and XML. It is a combination of web technologies that are used to develop a dynamic web application that sends and retrieves data from the server in the background without reloading the whole page. JSON(JavaScript Object Notation) is a format in which we store data and can transfer data from one system to another computer system. It is easy to understand and language-independent. AJAX can transport any kind of data either in JSON or any plain text. So in this article, we will learn how to send JSON Data using AJAX. Send JSON Data To send JSON data using AJAX follow the following steps − Step 1 − Create a new XMLHttpRequest instance. Step 2 − Set the request method that is open() method and URL. Step 3 − Set the request header to specify the data format. Here the content-type header is set to “application/json” which indicates that the data is going to send in JSON format. Step 4 − Create a call-back function that handles the response. Step 5 − Write JSON data. Step 6 − Convert the JSON data into strings using JSON.stringify() method. Step 7 − Now send the request using send() method along with the JSON data as the request body. Following is the flow chart which shows the working of the below code − 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(“JSON 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 data to the server qhttp.send(JSON.stringify({ “title”: “Mickey”, “userId”: 11, “id”: 21, “body”: “Mickey lives in london” })); } </script> <h2>Sending JSON Data</h2> <button type=”button” onclick=”sendDoc()”>Uplodaing Data</button> <div id=”sample”></div> </body> </html> Output Here in the above example, we send the following JSON document to the server at the given URL using the POST method − { “title”: “Mickey”, “userId”: 11, “id”: 21, “body”: “Mickey lives in london” } So when we click on the “Updating Data” button, the sendDoc() function is called. This function creates an XMLHttpRequest object. Then call the open() method of the XHR object to initialise the request with the HTTP POST method and the URL of the server which is “https://jsonplaceholder.typicode.com/todos”. Then call the setRequestHeader() method to set the content type of the request as JSON. After that calls send() function to send the request along with the JSON document. When the server receives the request, it adds the document. If the update is successful, then the callback function is called with “ready state = 4 (that means the request is completed)” and “status = 201(that means the server is successfully created a new resource)” Then the response from the server is displayed in the HTML file with the help of innerHTML property of the sample element. It also prints a message to the console representing that the JSON data was successfully sent. 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. Conclusion So this is how we can send JSON data using XMLHttpRequest. It is the most commonly used data transmission format because it is light in weight and easy to understand. Now in the next article, we will learn how to parse XML objects. Print Page Previous Next Advertisements ”;

AJAX – Issues

AJAX – Issues ”; Previous Next Every technology in this world has its bright side and its dark side similarly AJAX is a powerful technique which is used to develop dynamic and interactive web applications but it also has some challenges and issues. So, some of the common issues related to AJAX are − Cross-Domain Requests − In AJAX, the requests generally work with the same-origin policy. This policy restricts requests to the same domain for security purposes which means if you try to make an AJAX request in a different domain you will get a CORS error. So to overcome this error you need to reconfigure your system and allow cross-domain requests with the help of JSONP or proxy servers. Security Vulnerability − In AJAX, the requests can be attacked using XSS(cross-site scripting) or CSRF(cross-site request forgery). So to avoid such types of vulnerabilities we have to use input validation, output encoding, and CSRF protect tokens. Browser Support − Some of the browser”s versions do not support AJAX functionalities due to which the browser compatibility issue arises. So while using AJAX please check your browser if they can make or support AJAX requests or not. Performance Impact − If we do not optimize the AJAX request properly then it will affect the performance. If we transfer excessive data, unnecessary requests, frequent requests, or inefficient server-side processing these activities are responsible for slowing down the page loading time and can increase the load of the server. So always make a proper and optimized request. Search Engine Optimization(SEO) − Search engines often face challenges in indexing AJAX-driven content because old web crawlers do not execute JavaScript. It will affect the ranking and discovery of the web page in the search engines. Testing and Debugging − Due to the asynchronous behaviour of the request it is hard to debug AJAX codes. So to overcome this issue we have to use good debugging tools that can identify the issues and resolve them correctly. JavaScript Dependency − AJAX is generally dependent upon JavaScript. So if JavaScript is disabled in the web browser, we will not be able to use AJAX functionalities. So always enable JavaScript in the web browser for a better experience. Code complexity − AJAX codes are complex especially when handling asynchronous flow and managing responses. So to overcome this issue always create organized, maintainable, and clear code in which each concern is maintained in separate code so that developers can easily understand. Dependency Management − As we know that AJAX is implemented using various web technologies due to which it has to rely on external libraries or frameworks. So managing dependencies and updating them in a timely is the biggest challenge for AJAX especially when we are working with multiple components or plugins. Conclusion So these are the major issues faced by the AJAX applications. So understanding these issues we can make better use of AJAX in our application for optimal functionality, security and smooth user experience. So this is how we wrap up our AJAX tutorial. Print Page Previous Next Advertisements ”;

AJAX – File Uploading

AJAX – File Uploading ”; Previous Next AJAX provides a flexible way to create an HTTP request which will upload files to the server. We can use the FormData object to send single or multiple files in the request. Let us discuss this concept with the help of the following examples − Example − Uploading a Single File In the following example, we will upload a single file using XMLHttpRequest. So for that first we create a simple form which has a file upload button and the submit button. Now we write JavaScript in which we get the form element and create an event which triggers when we click on the upload file button. In this event, we add the uploaded file to the FormData object and then create an XMLHttpRequest object which will send the file using the FormData object to the server and handle the response returned by the server. <!DOCTYPE html> <html> <body> <!– Creating a form to upload a file–> <form id = “myForm”> <input type=”file” id=”file”><br><br> <button type=”submit”>Upload File</button> </form> <script> document.getElementById(”myForm”).addEventListener(”submit”, function(x){ // Prevent from page refreshing x.preventDefault(); // Select the file from the system // Here we are going to upload one file at a time const myFile = document.getElementById(”file”).files[0]; // Create a FormData to store the file const myData = new FormData(); // Add file in the FormData myData.append(“newFiles”, myFile); // Creating XMLHttpRequest object var myhttp = new XMLHttpRequest(); // Callback function to handle the response myhttp.onreadystatechange = function(){ if (myhttp.readyState == 4 && myhttp.status == 200) { console.log(“File uploaded Successfully”) } }; // Open the connection with the web server myhttp.open(“POST”, “https://httpbin.org/post”, true); // Setting headers myhttp.setRequestHeader(“Content-Type”, “multipart/form-data”); // Sending file to the server myhttp.send(myData); }) </script> </body> </html> Output Example − Uploading Multiple Files In the following example, we will upload multiple files using XMLHttpRequest. Here we select two files from the system in DOM with the attribute of file type. Then we add the input files in an array. Then we create a FormData object and append the input files to the object. Then we create an XMLHttpRequest object which will send the files using the FormData object to the server and handle the response returned by the server. <!DOCTYPE html> <html> <body> <!– Creating a form to upload multiple files–> <h2> Uploading Multiple files</h2> <input type=”file”> <input type=”file”> <button>Submit</button> <script> const myButton = document.querySelector(”button”); myButton.addEventListener(”click”, () => { // Get all the input files in DOM with attribute type “file”: const inputFiles = document.querySelectorAll(”input[type=”file”]”); // Add input files in the array const myfiles = []; inputFiles.forEach((inputFiles) => myfiles.push(inputFiles.files[0])); // Creating a FormData const myformdata = new FormData(); // Append files in the FormData object for (const [index, file] of myfiles.entries()){ // It contained reference name, file, set file name myformdata.append(`file${index}`, file, file.name); } // Creating an XMLHttpRequest object var myhttp = new XMLHttpRequest(); // Callback function // To handle the response myhttp.onreadystatechange = function(){ if (myhttp.readyState == 4 && myhttp.status == 200) { console.log(“File uploaded Successfully”) } }; // Open the connection with the web server myhttp.open(“POST”, “https://httpbin.org/post”, true); // Setting headers myhttp.setRequestHeader(“Content-Type”, “multipart/form-data”); // Sending file to the server myhttp.send(myformdata); }) </script> </body> </html> Output Conclusion So this is how we can upload files to the given URL with the help of XMLHttpRequest. Here we can upload any type of file such as jpg, pdf, word, etc and can upload any number of files like one file at a time or multiple files at a time. Now in the next article, we will learn how to create a FormData object using XMLHttpRequest. Print Page Previous Next Advertisements ”;

Fetch API – Request

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({

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 – Send PUT Requests

AJAX – Send PUT Requests ”; Previous Next The PUT request is used to update data on the web server. In this request, the data is sent in the request body and the web server will replace the existing data with the new data. If the specified data does not exist, then it will add the replacement data as a new record in the server. PUT request is quite different from the POST request in terms of the following points − PUT is used to update existing records whereas POST is used to add new records in the server. PUT request can be cached whereas POST request cannot be cached. PUT request is idempotent whereas POST request is non-idempotent. PUT request works as a specific whereas POST request works as an abstract. Syntax open(”PUT”, url, true) Where, the open() method takes three parameters − PUT − It is used to update data on the web server. url − url represents the file url or location which 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. How to send PUT Request To send the PUT 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 } 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 be sent 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 to update the data present on the server. XMLHttpRequestObjectName.send(JSON.stringify(JSONdata)) The following flow chart will show the working of the example − Example <!DOCTYPE html> <html> <body> <script> function updateDoc() { // Creating XMLHttpRequest object var uhttp = new XMLHttpRequest(); // Creating call back function uhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(“sample”).innerHTML = this.responseText; console.log(“Data update Successfully”) } }; // Updating the given file uhttp.open(“PUT”, “https://jsonplaceholder.typicode.com/todos/21″, true); // Setting HTTP request header uhttp.setRequestHeader(”Content-type”, ”application/json”) // Sending the JSON document to the server uhttp.send(JSON.stringify({ “title”: “ApplePie”, “userId”: 12, “id”: 32, “body”: “ApplePie is made up of Apple” })); } </script> <h2>PUT Request</h2> <button type=”button” onclick=”updateDoc()”>Updating Record</button> <div id=”sample”></div> </body> </html> Output The output returned by the server after clicking on the updating button. Here in the above code, we are updating an existing record, so for updating we create a JSON document. To update the data we click on the “Updating Record” button. So when we click on the “Submit” button, the updateDoc() function is called. This function creates an XMLHttpRequest object. Then call the open() method of the XHR object to initialise the request with the HTTP PUT method and the URL of the server which is “https://jsonplaceholder.typicode.com/todos/21”. Then call the setRequestHeader() method to set the content type of the request as JSON. After that calls send() function to send the request along with the JSON document. When the server receives the request, it updates the specified record with the new data. If the update is successful, then the callback function is called with “ready state = 4 (that means the request is completed)” and “status = 200(that means the successful response)” Then updated data will display on the screen. It also prints a message to the console representing that the data was updated successfully. 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. NOTE − While you are working with the PUT method it is necessary to mention the record id in the URL like that “https://jsonplaceholder.typicode.com/todos/21”. Here we are updating a record whose id is 21. Conclusion So this is how we can send PUT requests using XMLHttpRequest. It is generally used to update or modify the data present on the server. Now in the next article, we will learn how to send JSON data. Print Page Previous Next Advertisements ”;