7

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 ?

Arty
  • 859
  • 2
  • 12
  • 31

7 Answers7

5

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.

Baris Demiray
  • 1,539
  • 24
  • 35
2

To get json

console.log(JSON.stringify(response));

To get structured JSON

console.log(JSON.stringify(response, undefined, 2));
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
2

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.

Elisha Sterngold
  • 2,324
  • 1
  • 16
  • 14
1

Use the JSON.parse function like as below:

JSON.parse(response, null, 2)
Ali Torki
  • 1,929
  • 16
  • 26
1

use console.dir(object:any) like this ->

$.ajax(sendquery).done(function (response) {
    console.dir(response);
});
  • 1
    when i write this way "console.dir('Survey Request :' +response)" it doesnt work but this is "console.dir(response)" working. – Arty Oct 17 '18 at 09:19
1

The best way is pass the display string in the first argument and the object as second

 console.log('Survey Request', response);

enter image description here

Sujit.Warrier
  • 2,815
  • 2
  • 28
  • 47
1

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.