<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vivek Mittal on Medium]]></title>
        <description><![CDATA[Stories by Vivek Mittal on Medium]]></description>
        <link>https://medium.com/@vivekmittal199?source=rss-60b1e1c2aac5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QfrUbR-f8a7WDf6Y_IMZ7A.jpeg</url>
            <title>Stories by Vivek Mittal on Medium</title>
            <link>https://medium.com/@vivekmittal199?source=rss-60b1e1c2aac5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:39:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivekmittal199/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Object.seal(), Object.freeze(), and Object.preventExtensions() in JavaScript]]></title>
            <link>https://medium.com/@vivekmittal199/understanding-object-seal-object-freeze-and-object-preventextensions-in-javascript-921fef0838ca?source=rss-60b1e1c2aac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/921fef0838ca</guid>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vivek Mittal]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 06:25:34 GMT</pubDate>
            <atom:updated>2023-10-21T06:25:34.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>JavaScript is a versatile and powerful programming language, known for its ability to manipulate and manage objects. Three essential methods for controlling the mutability of objects in JavaScript are Object.seal(), Object.freeze(), and Object.preventExtensions(). These methods play a crucial role in ensuring the integrity and immutability of objects, providing developers with the tools they need to maintain data consistency and security. In this article, we&#39;ll explore each of these methods in detail and understand their use cases.</p><h3>1. Object.seal()</h3><p>The Object.seal() method is used to seal an object, which means that it prevents the addition or removal of properties from that object. It also makes all existing properties non-configurable, meaning they cannot be reconfigured or deleted. However, the values of the existing properties can still be modified.</p><pre>const sealedObject = {<br>  name: &#39;John&#39;,<br>  age: 30<br>};<br><br>Object.seal(sealedObject);<br><br>// Adding a new property is not allowed<br>sealedObject.location = &#39;New York&#39;; // Error<br><br>// Deleting properties is not allowed<br>delete sealedObject.age; // Error<br><br>// Modifying existing properties is allowed<br>sealedObject.name = &#39;Jane&#39;;</pre><p>Use cases for Object.seal():</p><ul><li>When you want to prevent the addition or deletion of properties, but still allow property value changes.</li><li>Ensuring that certain properties remain consistent and unaltered throughout the object’s lifetime.</li></ul><h3>2. Object.freeze()</h3><p>The Object.freeze() method takes the concept of immutability a step further. When you freeze an object, it becomes completely immutable. This means that not only can you not add or delete properties, but you also cannot modify the values of existing properties.</p><pre>const frozenObject = {<br>  name: &#39;Alice&#39;,<br>  age: 25<br>};<br><br>Object.freeze(frozenObject);<br><br>// Adding a new property is not allowed<br>frozenObject.location = &#39;Paris&#39;; // Error<br><br>// Deleting properties is not allowed<br>delete frozenObject.age; // Error<br><br>// Modifying existing properties is not allowed<br>frozenObject.name = &#39;Bob&#39;; // Error</pre><p>Use cases for Object.freeze():</p><ul><li>When you need to create objects with constant, unchanging data.</li><li>Ensuring that data remains consistent and cannot be unintentionally modified.</li></ul><h3>3. Object.preventExtensions()</h3><p>The Object.preventExtensions() method is used to prevent the addition of new properties to an object. While it doesn&#39;t affect the configurability or writability of existing properties like Object.seal(), it stops the object from being extended with new properties.</p><pre>const extendedObject = {<br>  name: &#39;Eve&#39;,<br>  age: 28<br>};<br><br>Object.preventExtensions(extendedObject);<br><br>// Adding a new property is not allowed<br>extendedObject.location = &#39;Berlin&#39;; // Error<br><br>// Deleting properties is allowed<br>delete extendedObject.age;<br><br>// Modifying existing properties is allowed<br>extendedObject.name = &#39;Charlie&#39;;</pre><p>Use cases for Object.preventExtensions():</p><ul><li>When you want to prevent new properties from being accidentally added to an object while still allowing modification and deletion of existing properties.</li><li>Ensuring that an object has a fixed set of properties without any extensions.</li></ul><h3>Conclusion</h3><p>In JavaScript, the Object.seal(), Object.freeze(), and Object.preventExtensions() methods provide developers with ways to control the mutability of objects, based on their specific requirements. By applying these methods appropriately, you can enhance the security and stability of your code, reduce the risk of unintentional data changes, and ensure that your objects behave as expected throughout their lifecycle. Understanding when and how to use these methods is essential for mastering JavaScript&#39;s object manipulation capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=921fef0838ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built my portfolio using Next.js, TailwindCSS, TypeScript and Framer Motion]]></title>
            <link>https://medium.com/@vivekmittal199/how-i-built-my-portfolio-using-next-js-tailwindcss-typescript-and-framer-motion-8e7b2f82cfa1?source=rss-60b1e1c2aac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7b2f82cfa1</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[framer-motion]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Vivek Mittal]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 11:41:58 GMT</pubDate>
            <atom:updated>2022-03-21T11:41:58.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Vivek Mittal (Portfolio)" src="https://cdn-images-1.medium.com/max/1024/1*ueHj2zMEhMeytAjcQILHcg.png" /></figure><p>By mid february’22 while serving my notice period I decided to migrate my portfolio from CRA to next.js and also gave a thought about adding the blogs to my own <a href="https://vivekmittal.vercel.app/">portfolio website</a>. So I decided to go with the following tech stack listed below:</p><p>1. Next.js<br>2. TypeScript<br>3. Framer Motion<br>4. TailwindCSS<br>5. SendGrid</p><h3>Next.js</h3><p><a href="https://nextjs.org/">Next.js</a> is a production ready framework for <a href="https://reactjs.org/">React</a>. It comes with some great features out of the box like SSR/SSG/ISR, route pre-fetching, file system based routing, and most importantly SEO. So when I created my portfolio with CRA the TypeScript support is not good along with poor SEO. The need to have a separate backend server just to make your contact form working was a nightmare (if one is not using <a href="https://www.netlify.com/">Netlify</a>).<br>Due to all the above problems I decided to go with Next.js</p><h3>TypeScript</h3><p><a href="https://www.typescriptlang.org/">TypeScript</a> is a superset of JavaScript which provides optional typing and compiles down to JavaScript. While working with JavaScript I would occasionally struggle with type of a variable/object or any data type. That’s where TypeScript comes to the rescue and let’s us make our application type safe from the beginning itself.<br>Once you’re introduced with TypeScript, you will never go back to writing JavaScript.</p><h3>Framer Motion</h3><p><a href="https://www.framer.com/motion/">Framer Motion </a>is a production ready animation library for React. I felt the need to add some “cool” animations to my portfolio so that it looks more alive and interactive. One can argue between choosing <a href="https://react-spring.io/">React Spring</a> or <a href="https://github.com/chenglou/react-motion">React Motion</a> but that depends on the use-case and since I’ve already worked with Framer motion before so I went with this.</p><h3>TailwindCSS</h3><p><a href="https://tailwindcss.com/">TailwindCSS</a> is a utility first CSS framework which is highly customisable and can be optimised using PurgeCSS. It helps in building complex responsive layouts easily.</p><h3>SendGrid</h3><p>So I’ve a contact form in my portfolio website and I was going to host it on <a href="https://vercel.com/">Vercel</a> and not Netlify so I was in need of an emailing service to work flawlessly with my contact form which can be customised according to my needs as well. Then I did some research and came across <a href="https://sendgrid.com/">SendGrid</a> which can be easily integrated with Next.js (thanks to the ability of Next.js to add server code) and decided to use this.</p><h3>Miscellaneous</h3><p>There are some other packages such as remark-prism, react-toastify, react-icons and next-pwa which I used to add syntax highlighting, notifications, icons and make my application a progressive web app (PWA) respectively.</p><h3>Conclusion and what’s next?</h3><p>It took me around 2 weeks on and off to complete my portfolio website.<br>Down the road, I’ll add sitemap, optimise it further for mobile devices, add reactions to blog-posts, add a CDN to serve static-images and maybe use a CMS to store and fetch all my blogs/projects data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7b2f82cfa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Pokedex using HTML5, CSS3 and Vanilla JavaScript.]]></title>
            <link>https://medium.com/@vivekmittal199/create-a-pokedex-using-html5-css3-and-vanilla-javascript-d367681cc63d?source=rss-60b1e1c2aac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d367681cc63d</guid>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Vivek Mittal]]></dc:creator>
            <pubDate>Sat, 23 May 2020 19:35:50 GMT</pubDate>
            <atom:updated>2020-05-23T19:35:50.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a Pokemon Deck using HTML5, CSS3 and Vanilla JavaScript.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dJjCTOwtykMLKL4V" /></figure><p>Who doesn’t like Pokemon? Well no one!! 😍<br>This was one of my favorite shows which I used to watch in my childhood.</p><p>So, let’s create a deck of some of the pokemons using HTML, CSS and JavaScript.</p><p>Since I explained some of the famous AJAX requests methods in my previous blog, so for fetching the data about our pokemons, we are going to use Fetch API.<br>If you don’t know what Fetch is or maybe you forgot about it, well you can read my last blog to get basic understanding of it or refresh your knowledge about it. 👇<br><a href="https://medium.com/@vivekmittal199/ajax-4-way-requests-a9dd5531093e"><strong>(Ajax 4 Way Requests)</strong></a></p><h3>What we will create &amp; learn?</h3><p>We are going to create a Pokemon Deck with a total of 50 pokemons in it with their name, id and image.<br>Through this, we will learn following things:<br>1. Fetching data from an API<br>2. Promises in JavaScript<br>3. Writing HTML inside JavaScript</p><p>Our final project will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhVaDpUgYvsC3w5M9hqHVQ.png" /></figure><p><em>So lets dive right in!</em></p><p>We will create a new folder and place our index.html, style.css and app.js file in it.<br>In our index.html, we are going to create an <strong><em>unordered list </em></strong>with an id of <strong>pokedex</strong><br>Well, that’s it for our html file and it will look look this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;</pre><pre>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot; /&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>&lt;title&gt;Pokedex&lt;/title&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; /&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>&lt;h1&gt;Pokedex&lt;/h1&gt;<br><strong>&lt;ul id=&quot;pokedex&quot;&gt;&lt;/ul&gt;</strong><br>&lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p>Since, the CSS file is somewhat lengthy and my main focus here is not styling but JS, so I’ll not paste it here but you can access it from my github repo or else try styling it on your own (I know you can do it 😉).</p><h3>1. Fetching data from an API</h3><p>The API I’m using for fetching pokemon data is <strong>(</strong><a href="https://pokeapi.co/api/v2/pokemon"><strong>https://pokeapi.co/api/v2/pokemon</strong></a><strong>/)</strong></p><p>So our app.js will look like this:</p><pre>const getPokemon = () =&gt; {<br>  const url = &#39;<a href="https://pokeapi.co/api/v2/pokemon/1&#39;"><strong>https://pokeapi.co/api/v2/pokemon/1</strong>&#39;</a>;<br>  fetch(url)<br>   .then(res =&gt; res.json())<br>   .then(data =&gt; console.log(data))<br>}</pre><pre>getPokemon();</pre><p>As you can see I’ve added a number ‘1’ at the end of my url, it is the id of that pokemon. There are 500+ pokemons stored here and we are not going to fetch every single one of them. For this project we will fetch the data of starting 50 only.<br>Okay, so the above code will return an object with many properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*OKSb2eWrqc1Ab6XSVUObSw.png" /></figure><p>Here the important properties for us are <strong>id, name </strong>and <strong>image</strong>. But wait… there is no <strong>image</strong> property !! 🤨<br>Well, the image is stored in <strong>sprites</strong> with a property of <strong>front_default </strong>.</p><p>Okay, so we are able to fetch the data of a specific pokemon using its id at the end of the URL.</p><p><strong>So how to fetch the data of 50 pokemons? </strong>We can use a <strong>for loop</strong> and iterate over each and every pokemon and then console.log() it to see what happens.</p><p>Our code will look like this:</p><pre>const getPokemon = () =&gt; {<br>  <strong>for(let i = 1; i &lt;= 50; i++) {</strong><br>    const url = `<a href="https://pokeapi.co/api/v2/pokemon/$%7Bi%7D%60">https://pokeapi.co/api/v2/pokemon/${i}`</a>;<br>    fetch(url)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; console.log(data))<br>  <strong>}</strong><br>}</pre><pre>getPokemon();</pre><p>Here, we are looping through the starting 50 pokemons.<br>There is something called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"><strong>Template Literals</strong></a><strong> </strong>in JavaScript with the help of which we are able destructor our URL and use our <strong>i </strong>variable inside it.</p><p>Since, we want only id, name and image of every pokemon, so we will create an empty object and store these properties in that object.<br>The code will look like this:</p><pre>const getPokemon = () =&gt; {<br>  for(let i = 1; i &lt;= 50; i++) {<br>    const url = `<a href="https://pokeapi.co/api/v2/pokemon/$%7Bi%7D%60">https://pokeapi.co/api/v2/pokemon/${i}`</a>;<br>    fetch(url)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; {<br>      <strong>const pokemon = {};<br>      pokemon[&#39;id&#39;] = data.id;<br>      pokemon[&#39;name&#39;] = data.name;<br>      pokemon[&#39;image&#39;] = data.sprites[&#39;front_default&#39;];<br>      <br>      console.log(pokemon);</strong><br>    })<br>  }<br>}</pre><pre>getPokemon();</pre><p>The result will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*6P9_LoZ2m6pWc3apOrpXHA.png" /></figure><p>So now we are able to extract the properties which we need.<br>Let’s say instead of accessing 50 pokemons, what if we were to access 500 pokemons?<br>It will take quite a time, and we won’t we able to do anything until this for loop finishes. So this is bad and that’s why we use something called <strong>Promises.</strong></p><h3>2. Promises in JavaScript</h3><p>Suppose we are fetching data of 500 pokemons, and the total time taken by all the pokemons is 500, but if we use Promise then the total time taken will be equal to the max time taken by an individual pokemon and instead of fetching data in a sequential manner, it will fetch data parallelly and hence save our time.</p><blockquote>This was just my simple way of explaining promise.<br>For a detailed explanation on Promise, you can visit <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>official MDN docs</strong></a><strong>.</strong></blockquote><p>We are going to use <strong>Promise.all()</strong> which will basically return a promise that resolves once all the passed in promises have resolved (i.e. successfully fetched).</p><p>We will start by having an empty array of Promises outside our for loop.<br>Inside the for loop, we will push the promise which is returned when <strong>fetch()</strong> is used. Like that we will push all our 50 promises inside that array.</p><p>Now we will use <strong>Promise.all() </strong>method by passing promises array as an argument and do a <strong>.then()</strong> and move that pokemon object we created.<br>So the code will look like this:</p><pre>const getPokemon = () =&gt; {<br>  const promises = [];<br>  <br>  for(let i = 1; i &lt;= 50; i++) {<br>    const url = `<a href="https://pokeapi.co/api/v2/pokemon/$%7Bi%7D%60">https://pokeapi.co/api/v2/pokemon/${i}`</a>;<br>    promises.push(fetch(url)<br>    .then(res =&gt; res.json()));<br>  }<br>  <br>  <strong>Promise.all(promises).then(result =&gt; {<br>      const pokemon = result.map((data) =&gt; ({<br>        id: data.id,<br>        name: data.name,<br>        image: data.sprites[&#39;front_default&#39;],<br>      }));<br>      <br>      console.log(pokemon);<br>    })</strong><br>}</pre><pre>getPokemon();</pre><p>Here we are creating the pokemon object by using a JavaScript inbuilt <strong>map()</strong> function which will map over all the items in the array.<br>After logging it to the console, we will get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*GamfJsUZFQE86PdPT2nQuQ.png" /></figure><p>Yay! Our object is created and we are done with fetching the data. 🥳</p><h3>3. Writing HTML inside JavaScript</h3><p>Our final step is rendering this data on our screen.<br>Remember, in our HTML file, we created an <strong>unordered list. </strong>We are going to render all this data in that list.</p><p>First, we need to select that list, and we will use <strong>document.getElementById() </strong>for that.</p><p>Now, I’m going to create another function called <strong>displayPokemon() </strong>and it will take pokemon object as an argument and then we will create a string inside of this function and render all our html inside of it.<br>We are going to use our <strong>map()</strong> again and render a &lt;li&gt;...&lt;/li&gt; <br>Final code looks like this:</p><pre><strong>const pokedex = document.getElementById(&#39;pokedex&#39;);</strong></pre><pre>const getPokemon = () =&gt; {<br>  const promises = [];<br>  <br>  for(let i = 1; i &lt;= 50; i++) {<br>    const url = `<a href="https://pokeapi.co/api/v2/pokemon/$%7Bi%7D%60">https://pokeapi.co/api/v2/pokemon/${i}`</a>;<br>    promises.push(fetch(url)<br>    .then((res) =&gt; res.json()));<br>  }<br>  <br>  Promise.all(promises).then(result =&gt; {<br>      const pokemon = result.map((data) =&gt; ({<br>        id: data.id,<br>        name: data.name,<br>        image: data.sprites[&#39;front_default&#39;],<br>      }));<br>    <strong>displayPokemon(pokemon);</strong><br>    })<br>};</pre><pre><strong>const displayPokemon = (pokemon) =&gt; {<br>  const pokemonString = pokemon.map(singlePokemon =&gt; `<br>    &lt;li&gt;<br>      &lt;img src=&quot;${singlePokemon.image}&quot; /&gt;<br>      &lt;h3&gt;${singlePokemon.id}. ${singlePokemon.name}&lt;/h3&gt;<br>    &lt;/li&gt;`<br>  ).join(&quot;&quot;);<br>  <br>  pokedex.innerHTML = pokemonString;<br>};</strong></pre><pre>getPokemon();</pre><p>So we are able to write HTML inside JS using template literals which we used for our URL.</p><blockquote>Since a map function returns an array, so we used <strong>.join(&quot;&quot;)</strong> to convert it into a single string.</blockquote><p>We are using <strong>innerHTML </strong>to change the content of list to the created string.</p><p>Finally, we need to call <strong>displayPokemon()</strong> inside of our <strong>Promise.all()</strong></p><h3><strong>And we are done!! 🥳</strong></h3><p>If you like this blog then leave some claps👏 .</p><p>Final Project Codepen Link: <a href="https://codepen.io/vivek-mittal/pen/ExVMWOp">https://codepen.io/vivek-mittal/pen/ExVMWOp</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d367681cc63d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AJAX 4 way requests]]></title>
            <link>https://medium.com/@vivekmittal199/ajax-4-way-requests-a9dd5531093e?source=rss-60b1e1c2aac5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9dd5531093e</guid>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[xhr]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Vivek Mittal]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 20:54:48 GMT</pubDate>
            <atom:updated>2020-04-03T10:00:28.983Z</atom:updated>
            <content:encoded><![CDATA[<h3>AJAX 4 Way Requests</h3><p>In this blog, we’ll be learning about what is AJAX and what are the various ways of making an AJAX request by creating a simple <strong>Ron Swanson Random Quote Generator.</strong></p><p>You can access the finished project on this Codepen link below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fvivek-mittal%2Fembed%2Fpreview%2FdLKpqj%3Fheight%3D600%26slug-hash%3DdLKpqj%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fvivek-mittal%2Ffull%2FdLKpqj&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2982797.dLKpqj.small.c95c0dc3-6dba-4bec-b920-9335c62e01dd.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3730c1b7188d8f22e264a5ee1a008369/href">https://medium.com/media/3730c1b7188d8f22e264a5ee1a008369/href</a></iframe><p>All the web developers out there must have come across the term <strong>AJAX </strong>at-least once in their lifetime.</p><p>So what is AJAX?</p><ul><li>It stands for <strong><em>A</em></strong><em>synchronous </em><strong><em>J</em></strong><em>avaScript </em><strong><em>A</em></strong><em>nd </em><strong><em>X</em></strong><em>ML</em>.</li><li>It is NOT a Library, a Framework nor a Technology.</li><li>It is an approach with the help of which the user can send a request to the web server and get more content.</li></ul><blockquote><strong>A more formal definition will be:</strong></blockquote><ul><li>It is a functionality which allows web pages to be updated <strong>asynchronously </strong>by exchanging data with a web server behind the scenes.</li><li>AJAX makes it possible to update the parts of a web page without reloading the whole page which saves a lot of time and makes it convenient for the user.</li></ul><h3><strong>How AJAX Works?</strong></h3><p>For understanding how AJAX works, lets take an example of an application like <strong><em>Instagram</em></strong> where:</p><ul><li>A user scrolled down to the bottom.</li><li>Then, he asks for more content and then quickly, a request is made to the web server and the data is fetched from the server.</li><li>Now, the requested data is pulled from the server and it gets appended to the bottom of the page.</li><li>So the fetching of the data in the background is done with the help of AJAX.</li></ul><blockquote>You can fork the starter code from this Codepen link given below:</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fvivek-mittal%2Fembed%2Fpreview%2FabOQRMe%3Fheight%3D600%26slug-hash%3DabOQRMe%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fvivek-mittal%2Fpen%2FabOQRMe&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/112fe28967a384f5e121cbf9cd6b7dd4/href">https://medium.com/media/112fe28967a384f5e121cbf9cd6b7dd4/href</a></iframe><blockquote><strong>Now we will start with the very first way of making AJAX request with JavaScript</strong></blockquote><h3><strong>XMLHttp Request</strong></h3><p>So it is the first and very basic way of making requests to a web server.<br>All modern browsers have a built-in XMLHttpRequest object to request data from a server.<br>XHR code for our project looks like this:</p><pre>// url of our api which we will use<br>var url = &#39;<a href="https://ron-swanson-quotes.herokuapp.com/v2/quotes&#39;">https://ron-swanson-quotes.herokuapp.com/v2/quotes&#39;</a>;</pre><pre>// select button with this id and store in variable<br>var xhrbtn = document.querySelector(&quot;#xhr&quot;);</pre><pre>// select the paragraph of which we want to change the content<br>var display = document.querySelector(&quot;#quote&quot;);</pre><pre>xhrbtn.addEventListener(&quot;click&quot;, function(){<br>  var XHR = new XMLHttpRequest();<br>  XHR.onreadystatechange = function(){<br>    if(XHR.readyState == 4 &amp;&amp; XHR.status == 200){<br>      var quote = JSON.parse(XHR.responseText);<br>      display.innerText = quote;<br>    }<br>  }<br>  XHR.open(&quot;GET&quot;, url);<br>  XHR.send()<br>});</pre><p>Code explanation:</p><pre>var XHR = new XMLHttpRequest();</pre><p>The above line creates an <strong>XMLHttpRequest</strong> object.</p><pre>XHR.onreadystatechange = function(){<br>    if(XHR.readyState == 4 &amp;&amp; XHR.status == 200){<br>      var quote = JSON.parse(XHR.responseText);<br>      display.innerText = quote;<br>    }<br>}</pre><p>The above <strong>onreadystatechange</strong> property specifies a function to be executed every time the status of the XMLHttpRequest object changes.</p><p>When <strong>readyState</strong> property is 4 and the <strong>status</strong> property is 200, the response is ready. <strong>JSON.parse()</strong> parses the JSON string and then it will be saved in quote variable.<br>Finally, we will display that quote in the text box.</p><pre>XHR.open(&quot;GET&quot;, url);</pre><p>This line above will open the get request for the URL.</p><pre>XHR.send();</pre><p>This line above sends the request to the server. In our case, the request is asynchronous(default), this method returns as soon as the request is sent and result is delivered using events.</p><h3>Fetch API</h3><p>The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.</p><blockquote>It provides a cleaner syntax and makes streaming possible.</blockquote><p>Fetch code for our project looks like this:</p><pre>var fetchbtn = document.querySelector(&quot;#fetch&quot;);</pre><pre>fetchbtn.addEventListener(&quot;click&quot;, function(){<br>  fetch(url)<br>  .then(function(req){<br>    req.json().then(function(data){<br>      display.innerText = data[0];<br>    })<br>  })<br>  .catch(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><p>Code Explanation:</p><pre>fetch(url)</pre><p>As the name says, it fetches the data from the parsed URL and then various functionalities can be performed on the fetched data.</p><pre>.then(function(req){<br>  req.json().then(function(data){<br>    display.innerText = data[0];<br>  })<br>})</pre><p>This function will run after the fetch(url) is completed and it will take a function with a req parameter as an input and here we are going to nest a .then() inside another .then() function.<br>Here, the req.json() will fetch the data from the URL and then .then(function(data){}) will retrieve the data attribute from that fetched object and finally we will display that data in our text field.</p><pre>.catch(function(){<br>  alert(&quot;ERROR!&quot;);<br>})</pre><p>This function will catch any kind of errors which may occur in case our .then() function won’t run properly or maybe we encounter any error while fetching the data from the URL.</p><h3>jQuery</h3><p>It is one of the popular third party library for sending requests with JavaScript.</p><blockquote>“The Write Less, Do More Javascript Library”</blockquote><p>The major drawback with the Fetch API is that it is not fully supported on all the browsers and that’s why we are going with jQuery .</p><p>Our code for jQuery looks like this:</p><pre>$(&#39;#jquery&#39;).click(function(){<br>  $.getJSON(url)<br>  .done(function(data){<br>    $(&#39;#quote&#39;).text(data[0]);<br>  })<br>  .fail(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><p>Code Explanation:</p><pre>$(&#39;#jquery&#39;).click(function(){});</pre><p>The above line is a short and clean syntax for selecting an element with id jquery and then adding an on click event listener to that element.</p><pre>$.getJSON(url)<br>  .done(function(data){<br>    $(&#39;#quote&#39;).text(data[0]);<br>  })<br>  .fail(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><p>We are parsing our URL and getting the data back as an object.<br>Here, the .done() function is similar to .then() function and .fail() function is similar to .catch() function of <strong>Fetch API</strong>.</p><blockquote>The major advantage of jQuery over Fetch and XHR is that it is supported by all the browsers and is flexible. It saves so much time, effort and is easy to integrate.</blockquote><h3>AXIOS</h3><p>It is also one of the popular third party library for sending requests with JavaScript.</p><blockquote>There is this site called <a href="http://youmightnotneedjquery.com/">http://youmightnotneedjquery.com/</a> which shows us that jQuery may not be saving us that much time and we need some other way of sending the request and doing other stuff.</blockquote><p>The main advantages of AXIOS over other type of requests we saw above are:</p><ul><li>Built on top of XHR API</li><li>Make http requests from Node.js</li><li>Supports the Promise API</li><li>Automatically transforms the JSON data</li><li>Intercepts, transforms and cancels requests</li></ul><p>Our code for AXIOS looks like this:</p><pre>var axiosbtn = document.querySelector(&quot;#axios&quot;);</pre><pre>axiosbtn.addEventListener(&quot;click&quot;, function(){<br>  axios.get(url)<br>  .then(function(res){<br>    display.innerText = res.data[0];<br>  })<br>  .catch(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><p>Code Explanation:</p><pre>axios.get(url)</pre><p>This line above makes a get request to the URL.</p><pre>.then(function(res){<br>  display.innerText = res.data[0];<br>})<br>.catch(function(){<br>  alert(&quot;ERROR!&quot;);<br>})</pre><p>The .then() will run after the axios.get(url) succeeds in getting the data from the parsed URL without any errors and will display the required data in the text field.<br>If any kind of errors are encountered, then our .catch() will run and will give an alert.</p><p>So our all the ways of making the AJAX requests are done and our final JavaScript will look like this:</p><pre>var url = &#39;<a href="https://ron-swanson-quotes.herokuapp.com/v2/quotes&#39;">https://ron-swanson-quotes.herokuapp.com/v2/quotes&#39;</a><br>var xhrbtn = document.querySelector(&quot;#xhr&quot;);<br>var fetchbtn = document.querySelector(&quot;#fetch&quot;);<br>var axiosbtn = document.querySelector(&quot;#axios&quot;);<br>var display = document.querySelector(&quot;#quote&quot;);</pre><pre>xhrbtn.addEventListener(&quot;click&quot;, function(){<br>  var XHR = new XMLHttpRequest();<br>  XHR.onreadystatechange = function(){<br>    if(XHR.readyState == 4 &amp;&amp; XHR.status == 200){<br>      var quote = JSON.parse(XHR.responseText);<br>      display.innerText = quote;<br>    }<br>  }<br>  XHR.open(&quot;GET&quot;, url);<br>  XHR.send()<br>});</pre><pre>fetchbtn.addEventListener(&quot;click&quot;, function(){<br>  fetch(url)<br>  .then(function(req){<br>    req.json().then(function(data){<br>      display.innerText = data[0];<br>    })<br>  })<br>  .catch(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><pre>$(&#39;#jquery&#39;).click(function(){<br>  $.getJSON(url)<br>  .done(function(data){<br>    $(&#39;#quote&#39;).text(data[0]);<br>  })<br>  .fail(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><pre>axiosbtn.addEventListener(&quot;click&quot;, function(){<br>  axios.get(url)<br>  .then(function(res){<br>    display.innerText = res.data[0];<br>  })<br>  .catch(function(){<br>    alert(&quot;ERROR!&quot;);<br>  })<br>});</pre><p>If you like this blog then leave as many claps 👏 as you can.<br>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9dd5531093e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>