DEV Community

Cover image for AJAX and Fetch API Crash Courses
The Dev Drawer
The Dev Drawer

Posted on • Edited on

AJAX and Fetch API Crash Courses

In my career, I have used both AJAX and Fetch API (more recently). If you have ever had to get remote data from an API or internal PHP URL, most likely you have used one or the other.

In this tutorial, I show you how to do both methods just in case you are only familiar with one or the other. We will be using PHP to create a JSON object that grabs a list of all countries (if I missed one, I am sorry, I copied a list).

AJAX has been tried and tested for years within jQuery and at one point was the go-to method. With Vanilla JS making a considerable comeback, new options like the built-it Fetch API are used more often. This is mostly due to its ease of use and since it is built into JavaScript, you no longer need a framework or library to use it.

View This On YouTube

File Structure

/index.html
/js/init.js
/src/functions.php

For simplicity, I will be pulling from a local PHP file that returns a JSON object that can then be consumed using AJAX or Fetch. You can use this PHP file for both methods. In the init.js file, you would add your AJAX or Fetch code listed below.

HTML Setup

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How To Use AJAX or Fetch</title>
    <style>
        .country-list { padding:0; margin:0;}
        .country-list li { list-style-type: none; display:block;}
    </style>
</head>
<body>
    <label>Using AJAX (jQuery)</label>
    <br>
    <input type="text" id="ajaxcountry" placeholder="Country Name">
    <br>
    <br>
    <label>Using Fetch (Vanilla JS)</label>
    <br>
    <input type="text" id="vanillacountry" placeholder="Country Name">
    <br>
    <ul class="country-list"></ul>
    <script src="/js/init.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

If you are using the AJAX method, you can add a reference to jQuery directly above the /js/init.js file reference. It will look like this:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
Enter fullscreen mode Exit fullscreen mode

Setup Our PHP File

In your /src/functions.php file you can add the following dummy data.

First, we need to add an array of countries. You can find such arrays on GitHub but mine should be pretty extensive. My entire PHP file is below so you can see where it goes.

<?php
// list of countries as an array to testing purposes
$countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "NewReunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Sa Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "moa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"];

$name = $_POST['search']; // get the search term that is entered into the search box
$match = []; // create an empty array

if(strlen($name) > 0) { // check if the search term is greater than 0 characters
    for ($i = 0; $i < count($countries); $i++) { // loop through the array
        $formArr = strtolower(substr($countries[$i], 0, strlen($name))); // get the first x characters of the array
        if(strtolower($name) == $formArr) { // check if the search term matches the array
            array_push($match, $countries[$i]); // add the array to the match array
        }
    }
}

echo json_encode($match); // return the array as a json object
Enter fullscreen mode Exit fullscreen mode

The PHP code should now be set for a response using AJAX or Fetch. It is simple code and can be replaced with a direct call to an API if you want, but to make this tutorial more simple, we are just calling a PHP file.

AJAX Method

In your /js/init.js file, you can use jQuery to reference the AJAX method.

NOTE: Make sure you have the jQuery tag added to your index.html file above.

$(document).ready(function () {
    $("#ajaxcountry").on("keyup", function () { // when keyup
        $.ajax({ // ajax call starts
            type: "POST", // POST method
            url: "/src/functions.php", // the file to call
            data: "search=" + $(this).val(), // value of the input
            success: function (response) { // data is returned from the php page
                $(".country-list").html(""); // remove all child nodes of the div
                $(".country-list").show(); // show the div
                $.each(JSON.parse(response), function (i, item) { // loop though the response
                    $(".country-list").append("<li>" + item + "</li>"); // append the response to the div
                });
            },
        });
    });
    $(".country-list").on("click", "li", function () { // when a list item is clicked
        var val = $(this).text(); // get the text of the clicked item
        selectCountry(val) // call the function to select the item
    });
});

function selectCountry(val) { // function to select the item
    $("#ajaxcountry").val(val); // set the value of the input to the value of the clicked item
    $(".country-list").hide(); // hide the div
}
Enter fullscreen mode Exit fullscreen mode

Using the code above, we initiate an AJAX call on the /src/functions.php file then parse the JSON results before appending them to our .country-list HTML object.

The on-click event for the .country-list element now should take the dynamic list and give you the ability to set the text box based on a selection.

Fetch API Method

NOTE: This method uses built-in functions on Vanilla JS so you don't need to add any references to jQuery.

window.addEventListener("load", function(e) { // when the page loads
    document.querySelector("#vanillacountry").addEventListener("keyup", function (e) { // when keyup
        fetch("/src/functions.php", { // fetch the file
            method: "POST", // POST method
            headers: { "Content-Type": "application/x-www-form-urlencoded" }, // set the content type
            body: "search=" + this.value // value of the input
        }).then(function (response) { // when the response is returned
            return response.text(); // return the response
        }).then(function (response) { // when the response is returned
            var countryList = document.querySelector(".country-list"); // get the country list
            countryList.innerHTML = ""; // remove all child nodes of the div
            countryList.style.display = "block"; // show the div
            JSON.parse(response).forEach(function (item) { // loop though the response
                var li = document.createElement("li"); // create a list item
                li.innerHTML = item; // set the text of the list item
                countryList.appendChild(li); // append the list item to the div
            });
        });
    });
});

document.querySelector(".country-list").addEventListener("click", function (e) { // when a list item is clicked
    if (e.target.tagName === "LI") { // if the clicked item is a list item
        selectCountry(e.target.innerHTML); // call the function to select the item
    }
});

function selectCountry(val) { // function to select the item
    document.querySelector("#vanillacountry").value = val; // set the value of the input to the value of the clicked item
    countryList.style.display = "none"; // hide the div
}
Enter fullscreen mode Exit fullscreen mode

So, if you are comparing AJAX to Fetch API, they are very similar. The code between the two almost mirror each other but one uses jQuery functions and the other uses JS functions.

Using the code above, we initiate a Fetch API call on the /src/functions.php file then parse the JSON results before appending it to our .country-list HTML object.

The on-click event for the .country-list element now should take the dynamic list and give you the ability to set the text box based on a selection.

Conclusion

Personally, I like Fetch API. I used jQuery for so long, that I forgot how to use Vanilla JS, but once I was able to really get back into it I felt that it is better since it is faster and has a much smaller footprint on my servers.

You can use either depending on your needs. Fetch is riding the comeback of Vanilla JS and gives you a lot more flexibility if you plan on using other frameworks outside of jQuery (React, Vue, etc).

Read more articles on DevDrawer

Top comments (5)

Collapse
 
rhf profile image
Bob Fletcher

This is an excellent write up showing examples of both AJAX and vanilla JS using fetch. It is exactly what I have been looking for.
Thanks.

Collapse
 
thedevdrawer profile image
The Dev Drawer

That is good to hear. I have been doing a lot of React lately but I love to see vanilla being used too.

Collapse
 
loveliberty profile image
Love Liberty

That's great information about fetch().

There are some basic things I don't understand.

If the server has loaded a PHP script, does the PHP have to use echo to make the data available in .response /.responseText?

If the PHP uses echo won't that appear by default on the screen?

Collapse
 
thedevdrawer profile image
The Dev Drawer

Yes, it does for the most part. You are looking for a response. In my example, it is a very simple GET response so it echos out the data because the API is essentially just displaying data from the database in a way that you can fetch it on the frontend.

When you are working with an API endpoint, you have various methods of communicating your data. GET would be the simplest as it displays the data as JSON. You also have PUT for updating, POST for inserting, and DELETE for deleting. Those endpoints do not have to return the data but the response of success or fail. If you are doing a GET like I did in the tutorial, you would want to echo your content if the API is built with PHP your your fetch request can receive the data as it is expected, otherwise you would just echo the correct response of success or fail.

I hope I understood your question and answered it accordingly. If not, let me know and I will try again.

Collapse
 
tryingtolearn profile image
tjd

Thanks for a great write up. Clear and concise, a tremendous help!!