How to do using a REST point and using AJAX & jQuery to loop through the items and display?

How to do using a REST point and using AJAX & jQuery to loop through the items and display?
0

#1

The question that I was asked was :
– use this REST point https://melita.com/wp-json/mobile/v1/internationalcountries and using AJAX & jQuery loop through the items and
display all the country name of “name”: “Group 5” only.

How do I do that?
Any help would be really appreciated?


#2

hey @deni404 are you sure that is the right URL?


#3

@jamesfmac I corrected the link,sorry about that.


#4

@deni404 that endpoint has ‘Access-Control-Allow-Origin’ header is present on the requested resource’ i.e. it’s set to not allow access from other domains.

Are you attempting to get the data from the same domain? If not the GET request will error


#5

Are you getting the data, and simply wondering how to filter that data? Or are you running into the CORS (cross-origin) problem, where Melita’s security won’t allow your script to fetch() that resource?


#6

If it’s a question of how to process the JSON object you get from that URL, then its probably just a matter of converting the string to a JSON object, and walking through the JSON itself.

If it’s a matter of how to fetch that data, I’d take a look at the vanilla javascript fetch() API. Very sweet, very clean, and pretty intuitive.

In either case, I put together a fiddle that should show you how to parse that JSON object.

let countriesJSON = /* I've removed the JSON string, as it was REALLY long */;

let countriesObj = JSON.parse(countriesJSON);

/****
 * Everything above could have been done via a fetch, assuming the site allows CORS.
 *  That would look more like the following:
 * 
 *  let melitaUrl = 'https://melita.com/wp-json/mobile/v1/internationalcountries';
 *  // Get a javascript Promise using the fetch() API
 *  fetch(melitaUrl)
 *     // When the fetch() completes, we get a response object
 *     .then( (response) => {
 *        // that response object has a json conversion.
 *        return response.json()
 *      })
 *     // Use the json  object we just returned in the then()
 *     .then( (countriesObj) => {
 *        // All the code below would work exactly the same
 *        //  here, as the json object is the same.
 *      })
 *  
 ****/

// We can filter that json object, finding just the one with
//  the name = "Group 5". It returns an array, but an array
//  with a length of one.
let group5Countries = countriesObj.international_countries.filter((group) =>  group.name == "Group 5")[0];

// Let's store a reference to the UL in the HTML DOM.
let myContainer = document.querySelector("#countries-pane");

// We can iterate over the entire collection of countries
//  in that group 5 collection, and do something with each. 
group5Countries.countries.map(country => {
  // We'll create an LI element, to stick into that UL
  let myLiEl = document.createElement("li");
  // And we'll fill that LI with information about each particular
  //  country!
  myLiEl.innerText = `Country: ${country.country}, code: ${country.country_code}`;
  
  // Lastly, we can append that LI into the UL.
  myContainer.appendChild(myLiEl);
})

I’ve removed the Melita-specific code from the above, both because it’s not mine to share and because it’s a REALLY large JSON object. But the process is simply this: create the JSON from the string, then process through the string.

First, you want to filter international_countries for the one whose name property is Group 5. Then, you can use .map() to do something with each member of the countries array within that reduced list. Whether you use jQuery or not, the process is much the same.


#7

@deni404 Similar to the answer already provided, if you have the data returned you could use the below to extract a list of relevant country names.

// the function accepts two params:
// 1. The JSON object returned by your API (once the CORS issue is resolved and a group name
// 2. The group name that you want to extract the country names for 
const getCountryNamesFromGroup = function (countryList, groupName){
    return countryList.international_countries
            .filter(x=>x.name == groupName)[0]
            .countries
            .reduce((accumulator, curVal,CurIndex)=>
            {
                accumulator.push(curVal.country)
                return accumulator
            },[] )
}