{"id":13566,"date":"2022-03-16T12:13:08","date_gmt":"2022-03-16T12:13:08","guid":{"rendered":"http:\/\/www.max-sperling.bplaced.net\/?p=13566"},"modified":"2024-02-16T10:47:02","modified_gmt":"2024-02-16T10:47:02","slug":"ajax-xhr-vs-fetch","status":"publish","type":"post","link":"http:\/\/www.max-sperling.bplaced.net\/?p=13566","title":{"rendered":"AJAX (XHR vs. Fetch API)"},"content":{"rendered":"<p><strong>AJAX<\/strong><br \/>\n&#8211; stands for &#8220;Asynchronous JavaScript and XML&#8221;<br \/>\n&#8211; allows asynchronous communications with the server<br \/>\n&#8211; is used to update web pages without reloading them<\/p>\n<p>(It&#8217;s normally also called AJAX if not used with XML.)<\/p>\n<hr>\n<p><strong>Example<\/strong> (with XHR and Fetch API)<\/p>\n<pre class=\"brush: xml; gutter: false; title: index.html; notranslate\" title=\"index.html\">\r\n&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n    &lt;head&gt;\r\n        &lt;script src=&#039;https:\/\/code.jquery.com\/jquery-latest.js&#039; defer&gt;&lt;\/script&gt;\r\n        &lt;script src=&#039;countries.js&#039; defer&gt;&lt;\/script&gt;\r\n    &lt;\/head&gt;\r\n    &lt;body&gt;\r\n        &lt;div&gt;\r\n            &lt;select id=&#039;variantSel&#039;&gt;\r\n                &lt;option value=&#039;xhr1&#039; label=&#039;via xhr (direct)&#039;&gt;&lt;\/option&gt;\r\n                &lt;option value=&#039;xhr2&#039; label=&#039;via xhr (jQuery)&#039;&gt;&lt;\/option&gt;\r\n                &lt;option value=&#039;fetch1&#039; label=&#039;via fetch (default)&#039;&gt;&lt;\/option&gt;\r\n                &lt;option value=&#039;fetch2&#039; label=&#039;via fetch (async\/await)&#039;&gt;&lt;\/option&gt;\r\n            &lt;\/select&gt;\r\n            &lt;button id=&#039;requestBtn&#039;&gt;Load countries (EU)&lt;\/button&gt;\r\n        &lt;\/div&gt;\r\n        &lt;div id=&#039;contentDiv&#039;&gt;\r\n        &lt;\/div&gt;\r\n    &lt;body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<pre class=\"brush: jscript; gutter: false; title: countries.js; notranslate\" title=\"countries.js\">\r\nconst requestBtn = document.getElementById(&#039;requestBtn&#039;);\r\nconst contentDiv = document.getElementById(&#039;contentDiv&#039;);\r\n\r\nrequestBtn.onclick = loadCountries;\r\n\r\nfunction loadCountries() {\r\n    contentDiv.innerHTML = &#039;&#039;;\r\n\r\n    const requestURL = &#039;https:\/\/restcountries.com\/v3.1\/subregion\/europe&#039;;\r\n    const variantSel = document.getElementById(&#039;variantSel&#039;);\r\n    const currentVal = variantSel[variantSel.selectedIndex].value;\r\n\r\n    switch (currentVal) {\r\n        case &#039;xhr1&#039;:\r\n            getWithXhr1(requestURL, writeCountries);\r\n            break;\r\n        case &#039;xhr2&#039;:\r\n            getWithXhr2(requestURL, writeCountries);\r\n            break;\r\n        case &#039;fetch1&#039;:\r\n            getWithFetch1(requestURL, writeCountries);\r\n            break;\r\n        case &#039;fetch2&#039;:\r\n            getWithFetch2(requestURL, writeCountries);\r\n            break;\r\n    }\r\n}\r\n\r\nfunction getWithXhr1(requestURL, callback) {\r\n    const xhr = new XMLHttpRequest();\r\n    xhr.open(&#039;GET&#039;, requestURL);\r\n    xhr.responseType = &#039;json&#039;;\r\n    xhr.onload = function() {\r\n        callback(xhr.response);\r\n    };\r\n    xhr.send();\r\n}\r\n\r\nfunction getWithXhr2(requestURL, callback) {\r\n    $.ajax({\r\n        url: requestURL,\r\n        dataType: &#039;json&#039;,\r\n        success: function(data) {\r\n            callback(data);\r\n        }\r\n    });\r\n}\r\n\r\nfunction getWithFetch1(requestURL, callback) {\r\n    fetch(requestURL)\r\n    .then(function(httpResponse) {\r\n        return httpResponse.json();\r\n    })\r\n    .then(function(jsonContent) {\r\n        callback(jsonContent);\r\n    });\r\n}\r\n\r\nasync function getWithFetch2(requestURL, callback) {\r\n    const httpResponse = await fetch(requestURL);\r\n    const jsonContent = await httpResponse.json();\r\n    writeCountries(jsonContent);\r\n}\r\n\r\nfunction writeCountries(countries) {\r\n    countries.forEach(function(country) {\r\n        const countryDiv = document.createElement(&#039;div&#039;);\r\n        countryDiv.innerHTML = country.name.common;\r\n        contentDiv.appendChild(countryDiv);\r\n    });\r\n}\r\n<\/pre>\n<hr>\n<p><strong>Comparison<\/strong><\/p>\n<table>\n<tr>\n<th>XHR<\/th>\n<th>Fetch API<\/th>\n<\/tr>\n<tr>\n<td>&#8211; Old school<br \/>&#8211; Works with Callbacks<\/td>\n<td>&#8211; New school<br \/>&#8211; Works with Promises<\/td>\n<\/tr>\n<\/table>\n","protected":false},"excerpt":{"rendered":"<p>AJAX &#8211; stands for &#8220;Asynchronous JavaScript and XML&#8221; &#8211; allows asynchronous communications with the server &#8211; is used to update<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false},"categories":[55],"tags":[],"_links":{"self":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/13566"}],"collection":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=13566"}],"version-history":[{"count":1,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/13566\/revisions"}],"predecessor-version":[{"id":16830,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/13566\/revisions\/16830"}],"wp:attachment":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=13566"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=13566"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=13566"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}