CyberJunkie
CyberJunkie

Reputation: 22674

jQuery Ajax: get specific object value

I'm accessing a dictionary REST API using Ajax.

$.ajax({
  url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",
  dataType : 'json',
  success: function(data) {
    //called when successful
    alert(data.word);
  },
  error: function(e) {
    //called when there is an error
    console.log(e.message);
  }
});

The response:

[
  {
    "textProns": [],
    "sourceDictionary": "ahd-legacy",
    "exampleUses": [],
    "relatedWords": [],
    "labels": [],
    "citations": [],
    "word": "cat",
    "text": "A small carnivorous mammal (Felis catus or F. domesticus) domesticated since early times as a catcher of rats and mice and as a pet and existing in several distinctive breeds and varieties.",
    "sequence": "0",
    "score": 0.0,
    "partOfSpeech": "noun",
    "attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition"
  }
]

In my test example I get an alert undefined on success. Most Ajax examples I saw use loops but I'm returning one result. How can I extract the word and text values from the objects?

Upvotes: 4

Views: 17480

Answers (3)

Jayamurugan
Jayamurugan

Reputation: 1825

You want to change the success function like this,

success: function(data) {
  alert(data[0].word);
}

I verified the value coming correctly.

jQuery AJAX

Upvotes: 3

dda
dda

Reputation: 6203

As you can see your response starts with [ and ends with ]. So your response is an array. Then, inside the array, you get objects (starting with { and ending with }). So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc. So in your case, if there's only one result, you can do data[0].word.

Upvotes: 7

sachleen
sachleen

Reputation: 31131

The response is an object inside of an array. Try data[0].word

Upvotes: 6

Related Questions