{"id":911,"date":"2017-11-17T18:46:27","date_gmt":"2017-11-17T23:46:27","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=911"},"modified":"2021-01-17T21:34:01","modified_gmt":"2021-01-18T02:34:01","slug":"javascript-intro-to-ajax","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2017\/11\/17\/javascript-intro-to-ajax\/","title":{"rendered":"JavaScript: Intro to AJAX"},"content":{"rendered":"\n<p>AJAX stands for <strong>A<\/strong>synchronous <strong>J<\/strong>avaScript <strong>A<\/strong>nd <strong>X<\/strong>ML. The basic concept is to use JavaScript and combine the fetching of XML (or JSON) data and make that data appear in some location of a web page without the page ever having been refreshed. This allows for dynamic content in an otherwise static page.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.w3schools.com\/xml\/ajax_intro.asp\">w3schools.com<\/a> describes it like this:<\/p>\n\n\n\n<div class=\"w3-panel w3-info intro\">\n<p>AJAX is a developer&#8217;s dream, because you can:<\/p>\n<ul>\n<li>Update a web page without reloading the page<\/li>\n<li>Request data from a server &#8211; after the page has loaded<\/li>\n<li>Receive data from a server &#8211; after the page has loaded<\/li>\n<li>Send data to a server &#8211; in the background<\/li>\n<\/ul>\n<p>For this intro, I followed along with the <a href=\"https:\/\/www.youtube.com\/watch?v=rJesac0_Ftw\">video tutorial<\/a> produced by Brad Schiff on the Youtube channel <a class=\"yt-simple-endpoint style-scope yt-formatted-string\" href=\"https:\/\/www.youtube.com\/channel\/UCHRp19HU7Y2LwfI0Ai6WAGQ\">LearnWebCode.<\/a> I coded along with the video using the <a href=\"https:\/\/atom.io\/\">Atom IDE.<\/a><\/p>\n<p>This tutorial details how to use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">XMLHttpRequest()<\/code> function to request JSON data, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">getElementById()<\/code> to insert the data into the web page, and some logic for iteration, error handling, and JSON parsing. Here is the complete JavaScript code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">\/\/ Global variables\nvar pageCounter = 1;\nvar btn = document.getElementById('btn');\nvar animalContainer = document.getElementById('animal-info');\n\nbtn.addEventListener(\"click\", function() {\n\n    var ourRequest = new XMLHttpRequest();\n    ourRequest.open('GET', 'https:\/\/learnwebcode.github.io\/json-example\/animals-' + pageCounter + '.json');\n    ourRequest.onload = function() {\n\n        \/\/ Add request error handling\n        if (ourRequest.status &gt;= 200 &amp;&amp; ourRequest.status &lt; 400) {\n            var ourData = JSON.parse(ourRequest.responseText);\n            renderHTML(ourData);\n        }\n        else {\n            console.log(\"We connected to the server, but it returned an error.\")\n        }\n    };\n\n    \/\/ Error handling for bad connections\n    ourRequest.onerror = function() {\n        console.log(\"Connection error\");\n    };\n\n    ourRequest.send();\n    pageCounter++;\n    \/\/ code to hide the button after 3 clicks\n    if (pageCounter &gt; 3) {\n        btn.classList.add(\"hide-me\");\n    }\n});\n\nfunction renderHTML(data) {\n    var htmlString = \"\";\n    for (i = 0; i &lt; data.length; i++) {\n\n        htmlString += \"&lt;p&gt;\" + data[i].name + \" is a \" + data[i].species + \" that likes to eat \"\n\n        \/\/ Loop through all liked foods\n        for (ii = 0; ii &lt; data[i].foods.likes.length; ii++) {\n            if (ii == 0) {\n                htmlString += data[i].foods.likes[ii];\n            }\n            else {\n                htmlString += \" and \" + data[i].foods.likes[ii];\n            }\n        }\n\n        htmlString += \" and dislikes \";\n\n        \/\/ Loop through all disliked foods\n        for (j = 0; j &lt; data[i].foods.dislikes.length; j++) {\n            if (j == 0) {\n                htmlString += data[i].foods.dislikes[j];\n            }\n            else {\n                htmlString += \" and \" + data[i].foods.dislikes[j];\n            }\n        }\n        htmlString +=  \".&lt;\/p&gt;\";\n    }\n    animalContainer.insertAdjacentHTML('beforeend', htmlString);\n};<\/pre>\n<\/div>\n\n\n\n<p>Here is what the final page looks like, loaded in an iframe. With each click of the &#8220;Fetch info for 3 new animals&#8221; button, the information for three new animals is added to the page using AJAX, read from JSON data stored on the web. The button will disappear after the third click.<\/p>\n\n\n\n<!-- iframe plugin v.5.2 wordpress.org\/plugins\/iframe\/ -->\n<iframe loading=\"lazy\" src=\"https:\/\/www.bluegalaxy.info\/js\/ajax_demo\/ajax_tutorial_1.html\" scrolling=\"no\" width=\"100%\" height=\"500\" id=\"iframe_drop_shadow\" class=\"iframe-class\" frameborder=\"0\"><\/iframe>\n\n\n\n\n<p><\/p>\n\n\n\n<p>The JSON data can be found at these locations:<br>\nhttps:\/\/learnwebcode.github.io\/json-example\/animals-1.json<br>\nhttps:\/\/learnwebcode.github.io\/json-example\/animals-2.json<br>\nhttps:\/\/learnwebcode.github.io\/json-example\/animals-3.json<\/p>\n\n\n\n<p>and looks like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[\n  {\n    \"name\": \"Meowsy\",\n    \"species\" : \"cat\",\n    \"foods\": {\n      \"likes\": [\"tuna\", \"catnip\"],\n      \"dislikes\": [\"ham\", \"zucchini\"]\n    }\n  },\n  {\n    \"name\": \"Barky\",\n    \"species\" : \"dog\",\n    \"foods\": {\n      \"likes\": [\"bones\", \"carrots\"],\n      \"dislikes\": [\"tuna\"]\n    }\n  },\n  {\n    \"name\": \"Purrpaws\",\n    \"species\" : \"cat\",\n    \"foods\": {\n      \"likes\": [\"mice\"],\n      \"dislikes\": [\"cookies\"]\n    }\n  }\n]<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Interesting concepts:<\/strong><\/h4>\n\n\n\n<hr class=\"wp-block-separator\" id=\"dashed_hr\"\/>\n\n\n\n<p>1.&nbsp; Fetching data with <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">XMLHttpRequest()<\/code>:<\/p>\n\n\n\n<p>a) Set up a request variable:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var ourRequest = new XMLHttpRequest();<\/pre>\n\n\n\n<p>b) Use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">open()<\/code> with GET and the URL to the data as arguments:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ourRequest.open('GET', 'https:\/\/learnwebcode.github.io\/json-example\/animals-1.json');<\/pre>\n\n\n\n<p>c) Get response text <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">ourRequest.responseText<\/code> and parse the JSON in one step using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">JSON.parse(data)<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var ourData = JSON.parse(ourRequest.responseText);<\/pre>\n\n\n\n<p>d) Send the request:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ourRequest.send();<\/pre>\n\n\n\n<hr class=\"wp-block-separator\" id=\"dashed_hr\"\/>\n\n\n\n<p>2. Use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">getElementById()<\/code> to update web page location:<\/p>\n\n\n\n<p>a) Create variable to hold the data:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var animalContainer = document.getElementById('animal-info');<\/pre>\n\n\n\n<p>b) Make a div id container in the HTML document:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;div id=\"animal-info\"><\/pre>\n\n\n\n<p>c) Use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">insertAdjacentHTML()<\/code> to insert the data into the HTML div container:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">animalContainer.insertAdjacentHTML('beforeend', htmlString);<\/pre>\n\n\n\n<p>For more information about the insertAdjacentHTML() function, see:<br>\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Element\/insertAdjacentHTML\">https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Element\/insertAdjacentHTML<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator\" id=\"dashed_hr\"\/>\n\n\n\n<p>3. Code to hide button (or other HTML element) via CSS update by adding a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">classList<\/code> to the CSS element.<\/p>\n\n\n\n<p>a) Add code like this to the JavaScript:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ code to hide the button after 3 clicks\nif (pageCounter > 3) {\n    btn.classList.add(\"hide-me\");\n}<\/pre>\n\n\n\n<p>b) &#8220;hide-me&#8221; is defined in the CSS file using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">visibility: hidden;<\/code><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"css\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">.hide-me {\n  visibility: hidden;\n  opacity: 0;\n  transform: scale(.75);\n}<\/pre>\n\n\n\n<hr class=\"wp-block-separator\" id=\"dashed_hr\"\/>\n\n\n\n<p>4. Use of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">addEventListener()<\/code><\/p>\n\n\n\n<p>a) <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">addEventListener()<\/code> is applied to the btn variable:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">btn.addEventListener(\"click\", function() { ... } );<\/pre>\n\n\n\n<p>which is tied to the button in the HTML:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var btn = document.getElementById('btn');<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;button id=\"btn\">Fetch info for 3 new animals&lt;\/button><\/pre>\n\n\n\n<p>b) <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">addEventListener()<\/code> takes two arguments. The first one is &#8220;click&#8221; and the second is a function definition.<\/p>\n\n\n\n<p>&#8220;click&#8221; is an event. See:<br>\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events\/click\">https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events\/click<\/a><\/p>\n\n\n\n<p>For more information about this function see:<br>\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/EventTarget\/addEventListener\">https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/EventTarget\/addEventListener<\/a><\/p>\n\n\n\n<p>For more information about AJAX, see:<br>\n<a href=\"https:\/\/www.w3schools.com\/js\/js_ajax_intro.asp\">https:\/\/www.w3schools.com\/js\/js_ajax_intro.asp<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>AJAX stands for Asynchronous JavaScript And XML. The basic concept is to use JavaScript and combine the fetching of XML (or JSON) data and make that data appear in some location of a web page without the page ever having been refreshed. This allows for dynamic content in an otherwise static page. w3schools.com describes it &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2017\/11\/17\/javascript-intro-to-ajax\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">JavaScript: Intro to AJAX<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44],"tags":[68,65,10,53,67,45,62,66],"class_list":["post-911","post","type-post","status-publish","format-standard","hentry","category-javascript-language","tag-addeventlistener","tag-ajax","tag-css","tag-getelementbyid","tag-insertadjacenthtml","tag-javascript","tag-json","tag-xmlhttprequest"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/911","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=911"}],"version-history":[{"count":32,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/911\/revisions"}],"predecessor-version":[{"id":3373,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/911\/revisions\/3373"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=911"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=911"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=911"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}