4

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?

1
  • 1
    +1 to the grammar police for revising my english Commented Aug 20, 2012 at 19:58

3 Answers 3

7

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.

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

2 Comments

I am getting output "undefined". What can be the problem??
im also get output "undefined".
6

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

Comments

3

You want to change the success function like this,

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

I verified the value coming correctly.

jQuery AJAX

Comments

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.