0

I'm trying to build a simple web app using JQuery. I'm trying to make an ajax request to the server the following way:

function getClients() {
    return $.ajax('/api/v1/clients',
                  {
                      headers: {
                          Authorization: 'Token ' + getCookie("auth_token")
                      }
                  });
}

I also do the following:

$(document).ready(function() {
    console.log(getClients());
});

So that I can see the result of my request. In the console I see the following:

{
  "readyState": 4,
  "responseText": "{\"count\":2,\"next\":null,\"previous\":null,\"results\":[{\"id\":2,\"group_set\":[1],\"first_name\":\"b\",\"last_name\":\"b\",\"username\":\"b\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null},{\"id\":1,\"group_set\":[1],\"first_name\":\"a\",\"last_name\":\"a\",\"username\":\"a\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null}]}",
  "responseJSON": {
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
      {
        "id": 2,
        "group_set": [
          1
        ],
        "first_name": "b",
        "last_name": "b",
        "username": "b",
        "telegram_id": null,
        "phone": null,
        "picture": null,
        "blocked": false,
        "telegram_user": null,
        "user": 2,
        "source": null
      },
      {
        "id": 1,
        "group_set": [
          1
        ],
        "first_name": "a",
        "last_name": "a",
        "username": "a",
        "telegram_id": null,
        "phone": null,
        "picture": null,
        "blocked": false,
        "telegram_user": null,
        "user": 2,
        "source": null
      }
    ]
  },
  "status": 200,
  "statusText": "OK"
}

(This output is made by clicking on "Copy object" in Firefox). However, if I change getClients() as shown below:

function getClients() {
    return $.ajax('/api/v1/clients',
                  {
                      headers: {
                          Authorization: 'Token ' + getCookie("auth_token")
                      }
                  }).responseJSON;
}

Then in the console I will get

undefined

Also, when I try to use the object's properties in code, I get an error that the properties are undefined. How is that and how do I fix this? Thank you.

  • 1
    What's your problem exactly? Are you just trying to access the JSON values from the response? – Nanoo Sep 09 '20 at 18:50

2 Answers2

1

getClients returns promise. Your code:

return $.ajax(...).responseJSON

reads responseJSON from promise object which is undefined. Promise returns result only when it is resolved (then())

You should leave getClients as is and change part in document ready like:

$(document).ready(function() {
  getClients().then(function(response) {
    const respJson = JSON.parse(response);
    console.log(respJson.responseJSON);
  });
})
MRsa
  • 666
  • 4
  • 8
0

Keep the getClients() function as seen below:

function getClients() {
    return $.ajax('/api/v1/clients',
                  {
                      headers: {
                          Authorization: 'Token ' + getCookie("auth_token")
                      }
                  });
}

Then use Bracket Notation to select properties:

var clientData = getClients();
var jsonData = clientData["responseJSON"];

var results = jsonData["results"];

console.log(results[0]["first_name"]); // Logs the "first_name" value from first results array

Since your JSON properties are strings, Bracket Notation is required. Otherwise, you could use, for example: clientData.responseJSON

Nanoo
  • 836
  • 8
  • 16
  • 1
    .... is ajax async????? I assume you need to use [.then()](https://api.jquery.com/deferred.then/) – gaetanoM Sep 09 '20 at 19:00
  • Hence, you cannot use the returned promise as a json result – gaetanoM Sep 09 '20 at 19:02
  • 1
    So how do you expect `clientData` to contain the result of the asynchronous function? – Barmar Sep 09 '20 at 19:02
  • @Barmar Have you seen the question? Doing: `console.log(getClients());` returns all of the JSON data. I think OP had trouble selecting the properties. – Nanoo Sep 09 '20 at 19:04
  • He's seeing that in the console, which has a dynamic link to the Promise, and shows the properties that were updated after the response was received. – Barmar Sep 09 '20 at 19:05