Dominic Norton
Dominic Norton

Reputation: 187

How to fix [object Object] Javascript error?

I would like to display a request from my JSON placeholder. I'm unsure where to start or even what is the right question to ask to resolve my error.

I understand why the error occurs as shown here (what does [object Object] mean?) I don't understand how to fix the problem. I know I would need to use console.log() but unsure how to return the specific values to a variable then display it on the screen.

HTML

<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>

Javascript

$(document).ready(function(){
  $("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos/1", function(title, completed){
      alert("Title: " + title + "\nCompleted: " + completed);
    });
  });
});

Expected result

  "Title": "delectus aut autem",
  "completed": success

Upvotes: 2

Views: 7245

Answers (2)

Mamun
Mamun

Reputation: 68933

title is an object, it is not the property you are thinking. You have to access the title property from title object.

Try title.title:

$(document).ready(function(){
  $("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos/1", function(title, completed){
      alert("Title: " + title.title + "\nCompleted: " + completed);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>

Upvotes: 1

Shivani Sonagara
Shivani Sonagara

Reputation: 1307

You can check example on https://jsonplaceholder.typicode.com/. Which shows that it returns the object rather than the single value. Example can be illustrated as below:

$(document).ready(function(){
  $(document).on('click','.btn', function(){
   $.get("https://jsonplaceholder.typicode.com/todos/1", function(result_object, completed){
     console.log(result_object);
     alert("Title: " + result_object.title + "\nCompleted: " + completed);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>

Upvotes: 1

Related Questions