Reputation: 898
I am writing a program with php
laravel
and react.js
. But i am very new to these. Anyway in react
, i am sending a API request with ajax
.
like this:
const sendquery = {
"async": true,
"crossDomain": true,
"url": url,
"method": "POST",
"headers": {
"Authorization": "Bearer " + tkid,
"Accept": "application/json",
"Content-Type": "application/json",
},
"processData": false,
"data": query
};
$.ajax(sendquery).done(function (response) {
console.log('Survey Request :' + response);
});
There are another API requests that are printing nicely when i console.log()
because they are in array type. But this must be json
. I tested API with Postman everything is OK. But still i have output like this:
Survey Request :[object Object]
Can anyone please help ?
Upvotes: 7
Views: 12903
Reputation: 21
While i acknowledge all answers above, it's important to point out why you seem to be getting that result on the console.
When you do this:
console.log('Survey Request :' + response);
You are basically trying to concatenate a primitive value 'Survey Reguest :'
with a complex value response
, which is an object. Javascript cannot convert an object response
to a primitive value. By simply replacing the +
with a ,
signifies that you are sending the response
object as a separate argument. Javascript then logs the arguments separately to the console.
Upvotes: 1
Reputation: 60
use console.dir(object:any) like this ->
$.ajax(sendquery).done(function (response) {
console.dir(response);
});
Upvotes: 1
Reputation: 2504
Another option apart from what @Beris Demiray wrote is to write:
console.log('Survey Request :', response);
Meaning to put the object as a second parameter in the log.
This will give you an object that you'll can open in the debugger. The reason why this option is better because JSON.stringify doesn't stringify all objects, and this lets you look into all objects.
Upvotes: 2
Reputation: 2879
The best way is pass the display string in the first argument and the object as second
console.log('Survey Request', response);
Upvotes: 1
Reputation: 1607
You can try with JSON.stringify(response)
but note that it doesn't work with all the types, see JSON.stringify doesn't work with normal Javascript array, for example.
Upvotes: 5
Reputation: 34004
To get json
console.log(JSON.stringify(response));
To get structured JSON
console.log(JSON.stringify(response, undefined, 2));
Upvotes: 2
Reputation: 2038
Use the JSON.parse function like as below:
JSON.parse(response, null, 2)
Upvotes: 1