Javascript fetch data from php

I am trying to fetch values from php file

api.php

      

my javascript page has code like this.(this code is not on page api.php)

            fetch('http://localhost/react_task/react-webpack-boilerplate/php/api.php', {
        method: 'get',
        // may be some code of fetching comes here
    }).then(function(response) {
            if (response.status >= 200 && response.status < 300) {
                return response.text()
            }
            throw new Error(response.statusText)
        })
        .then(function(response) {
            console.log(response);
        })

can you please guide me how to fetch value of variable from php file by using fetch.

asked Sep 9, 2016 at 14:33

Javascript fetch data from php

Manpreet OberoiManpreet Oberoi

3473 gold badges4 silver badges11 bronze badges

3

You are not echoing the value, so it won't be send.


answered Sep 9, 2016 at 14:36

7

Your php needs to output the value you want. A simple way to do this is to use echo. For example:

echo 'come!! fetch this value';

answered Sep 9, 2016 at 14:40

RickCoxDevRickCoxDev

1651 silver badge9 bronze badges

1

You should use echo to display it in php then it will be available in you JavaScript reponse.

answered Aug 26, 2019 at 1:35

TL;DR How can I use fetch() to return data from a PHP file?


Hi all. I am having difficulty using fetch() to return data from PHP. Specifically, I have a PHP script jout.php that defines a simple array:

 'world'
];
return json_encode($sampleArray);

How can I now use fetch() to print this array to the JavaScript console log?


I've tried the JS below:

const req = async function() {
    const resp = await fetch('jout.php');
    const json = await resp.json();
    console.log(json);
}
req();

But this fails on the resp.json() line with the error, SyntaxError: Unexpected end of JSON input

In the above code JS code, if I replace the file (jout.php) with a simple JSON file jout.json containing:

{
    "hello": "world"
}

then the data from the JSON file is indeed written to the console as expected.


I realize there are other ways of using fetch(), and I will indeed learn those ways. But right now I am hoping to learn this method, since these use the tools I have readily available to me. Once I get this method working, I will continue to learn the basics of async/await with fetch. After that, I can branch out to other ways of using fetch() (aside from with a PHP file).

Thanks in advance.


Edit: Issue resolved. /u/cawcvs pointed out that my PHP file needs to echo the JSON array. So I added the line echo json_encode($sampleArray); and my issue was resolved.

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


 lang="en">

     charset="UTF-8">
     http-equiv="X-UA-Compatible" content="IE=edge">
     name="viewport" content="width=device-width, initial-scale=1.0">
    </span>How To Use AJAX or Fetch<span>
    


    Using AJAX (jQuery)
    
type="text" id="ajaxcountry" placeholder="Country Name">

Using Fetch (Vanilla JS)
type="text" id="vanillacountry" placeholder="Country Name">
class="country-list">

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:


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.


// 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("
  • " + item + "
  • "); // 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).