Skip to content
Advertisement

Outputting JSON from Curl APi call to Ajax

I am working on a course project in which I am required to use php to make api calls.

The Ajax call looks like this:

JavaScript

The php api call looks like this:

JavaScript

This works perfectly. I have used the same routine to make similar calls go the geonames API and had no issues doing so as they provide the name of the root object returned. In the example above, it is called geonames

$output['data'] = $decode['geonames'];

I am trying to use this pattern to make a call to the accuweather API. For this however, I don’t have the name of the root object.

I used the routine above, changing that specific line of code to $output['data'] = $result; and voila, I can see where geonames is coming from.

JavaScript

At this point I thought: “Now I just need to do the same with the API call to Accuweather and I will be able to find what I need to type between the curly brackets on $output['data'] = $decode['what_goes_here?']; but when I tried that, the JSON return does not display an object like the one above.

The JSON returned from the accuweather API when called straight from my javascript file, or through the example in their website, looks like this:

JavaScript

I am asking for help with one of two things:

a) A way to decode that JSON object without knowing what that object name is and output that to the AJAX call, or;

b) Receive the decoded object on javascript and decode it to access its properties there.

I immensely thank you in advance.

Advertisement

Answer

Edit: I looked more into PHP and realized that I did not understand that the php routine was simply using bracket notation to access the properties of the decoded object: $decode['geonames'].

I carried on looking into it and realized that I could use JSON.parse() in my javascript file.

So I changed that specific line of code in the php file to $output['data'] = $result;

Then on my ajax call I can access the properties of the JSON returned after using calling JSON.parse(result.data) as shown below:

JavaScript

This is logged as:

JavaScript
Advertisement