3

as I'm still learning, after hours of trying I still couldn't work out how to manage this Ajax call in my WP and get it to work. What I want to do is extract the "price" (USD) into a variable for further use.

This is my JSON object:

{
"data": {
    "id": xx, 
    "name": "xx", 
    "symbol": "xx", 
    "rank": xx, 
    "quotes": {
        "USD": {
            "price": xx, 
            "volume_24h": xx, 
            "market_cap": xx, 
            "percent_change_1h": xx, 
        }
     }, 
     "last_updated": xx
  }, 
}

And here's what I'm currently doing:

(function(getPrice) {
    $j.ajax({
        url: 'https://widgets.coinmarketcap.com/v2/ticker/3012/',
        type: 'GET',
        async: false,
        data: 'data',
    }).then(function(data) {
        console.log(data);
    });
})();

This gets me to log the whole "data", but after Google and StackOverflow I am still stuck. I figured it was just "data.quotes.USD.price", but apparently it isn't.

I would be very thankful vor every advice!

1
  • 1
    Your variable name is data and the first property of the object is also data, so the access would start off as data.data. This is, of course, provided that the ajax method already parsed the response, otherwise you need to JSON.parse(data) first Commented Aug 6, 2018 at 16:21

1 Answer 1

4

You need data twice; one is your variable, one is the outer object in the response. The correct version would be:

console.log(data.data.quotes.USD.price);

var $j = jQuery;

(function(getPrice) {
  $j.ajax({
    url: 'https://widgets.coinmarketcap.com/v2/ticker/3012/',
    type: 'GET',
  }).then(function(data) {
    console.log(data.data.quotes.USD.price);
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Also note that I removed async: false (as it's terrible practice) and data: 'data' was not needed.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow. I feel incredibly stupid right now, because I have tried every possible version and nothing worked, though I would've never thought of that. So here's to me ugh. And thank you so so so much! (I would have never guessed this either.) I'll learn. Maybe. Someday.
@ClopinTrouillefou - We've all been there! You may consider using another variable name such as response instead, such as then(function(response){ - You'll then have a semantically easier to read output: response.data.quotes.USD.price.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.