0

I am working on a webpage where when I enter a word and press the button, it will show the meaning of the word. I am getting an [object Object] error instead of the meaning of the word.

Example: Word I entered: code

Result through API:

{"Verb": ["attach a code to", "convert ordinary language into code"], "Noun": ["a set of rules or principles or laws (especially written ones", "a coding system used for transmitting messages requiring brevity or secrecy", "(computer science"]}

JS:

var links={
    'meaning': 'link here',
}
var getMeaning = function(word){
    totalLink = links.meaning + word;
    var r = new XMLHttpRequest();
    r.open("GET",totalLink, false);
    r.send();
    var data;
    if (r.status===200){
        var resp= JSON.parse(r.responseText);
        data=resp;
    }
    else{
        data='Error while running AJAX';
    }
    return data;
}
var PDictionary = function(){
    this.meaning = getMeaning;
}

HTML:

<input id='a' type='text'><br>
<button id='b'>Do it</button>
<p class='out'></p>
<script  type="text/javascript">
    var dictionary = new PDictionary();

    function done(){
        get();
    }
    function get(){
        var word=document.getElementById('a').value;
        meaning = dictionary.meaning(word);
        document.querySelector('.out').innerHTML = meaning;
    }
    var button = document.querySelector('#b');
    button.addEventListener('click',function(){
        get();
    });
</script>

On my console RESPONSE tab, I am getting the meaning of the word but on the webpage, I get the error

3
  • Can you make a fiddle? Easier for us to debug.. Commented Mar 24, 2015 at 4:17
  • [object Object] is not an error. It's the string representation of an object. See: console.log(String({foo: 42}));. Just the property of the object that you want to access. Commented Mar 24, 2015 at 4:18
  • because you get the object instead of result print the object with its key to get the result ,right now it shows the whole object,,like Object['noun'] Commented Mar 24, 2015 at 4:20

1 Answer 1

1

You are not actually receiving an error when it returns [object Object]. That is just the string representation of your object. You will need to do something to pull the actual property names and values from the object itself. You could try a for loop like the example below.

var x, m = '';
for (x in meaning) {
    m += x + "<br />" + meaning[x].join("<br />") + "<br /><br />";
}

Here is a JSFiddle to give you an idea of how you could implement it into your own code. https://jsfiddle.net/up2jrzp6/

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

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.