1

I toke a look at stackoverflow and couldn't find any solution to that issue while at the exam the instructor told us that there is solution for that issue so the bug won't happen, when entering country that exists it works perfectly, but when entering country that doesn't exist, I got the alert that I made of "Failed" and then "Page not found" but it keeps showing the 404 error.

here is my code of the ajax call :

function showChosenCountry() {
    const countryName = $("#countryNameBox").val();
    if (countryName === "")
        return alert("Error: Enter country name!");

    $.ajax({
        url: `https://restcountries.eu/rest/v2/name/${countryName}`,
        statusCode: {
            404: function () {

                alert("Page not found");
            }
        },
        success: allCountries => {
            let divOfAllCountries = ``;
            for (const country of allCountries) {

                const currentCountryDiv = `<div class="card"> <img class="card-img-top" src="${country.flag}"> <div class="country card-body">  <br> Name: ${country.name} <br> Top Level Domain: ${country.topLevelDomain} <br> Capital: ${country.capital} <br> Currencies: ${JSON.stringify(country.currencies[0])} </div> </div>`
                divOfAllCountries += currentCountryDiv;
            }
            $("#countriesPresentation").html(divOfAllCountries);
        },
        error: () => {
            alert("Failed");
        }
    })
}

html:

<body>
<div id="userInterface"></div>
    <input id="countryNameBox" class="input-group-text" type="text">
    <button onclick="showChosenCountry()" class="btn btn-secondary"> Show chosen country </button>
    <button onclick="showAllCountries()" class="btn btn-secondary"> Show all countries </button>
</div>

<br>
<div id="countriesPresentation" class="row"></div>
<script src="https://code.jquery.com/jquery-3.4.1.js"
    integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="main.js"></script>

I tried to try and catch the success function and tried to try and catch the whole function but nothing worked and it keeps showing me the "404 error" in the console, here is an example of error I got when I wrote that country name: "dsadasds"

Got an error : main.js?attr=3igYNs_OYXo4Rw9VmV3qWhA0818Zvx9uG1mBv0ICjA4eJS6TCT82UterkqZtqcFfPUmU-Tby8ele2Vuf8UdyWg:1061 GET https://restcountries.eu/rest/v2/name/dsadasds 404

Thanks.

Daniel
  • 97
  • 10
  • Does this answer your question? [How to get response status code from jQuery.ajax?](https://stackoverflow.com/questions/5344145/how-to-get-response-status-code-from-jquery-ajax) or even more specific [Capture 404 status with jQuery AJAX](https://stackoverflow.com/questions/10931270/capture-404-status-with-jquery-ajax) – caramba Feb 21 '20 at 08:24
  • No, since both answers are showing the error which I don't want, I want to catch the error so It won't show it in the console.. – Daniel Feb 21 '20 at 08:31

0 Answers0