0

I make a jquery ajax call and get the async result after it is finished with await:

async () => {
  const result = await $.ajax (url);
  console.log (result);
}

But in result I have only the content of the response, I want to get the headers and status code and so on from thejqXHR object. How do I get this?

To answer Rituls question, I want to write something like:

const result = await $.ajax(url);
const content = result[0];
const jqxhr = result[1];
console.log ('content:', content, 'status:', jqxhr.status);

EDIT:

I tried the following workaround and get a strange behaviour (Code is typescript):

const result = await ajax (gondorHeaderUrl);
console.log ('ajax result:', result);
console.log ('typeof ajax result:', typeof result);

function ajax (url: string, settings?: JQuery.AjaxSettings): Promise<JQuery.jqXHR> {
  return new Promise (((resolve, reject) => {
    $.ajax (url, settings)
      .then ((data, textStatus, jqXHR) => {
          console.log ( 'jqXHR:', jqXHR);
          console.log ( 'typeof jqXHR:', typeof jqXHR);
          resolve (jqXHR);
        },
        (jqXHR, textStatus, errorThrown) => reject (jqXHR)
      );
  }));
}

Console:

jqXHR: Object { readyState: 4...................
typeof jqXHR: object
ajax result: <!DOCTYPE html PUBLIC ...............
typeof ajax result: string

Why is result different from jqxhr? When I wrap it into an object it works:

resolve ({j:jqxhr});
Galdor
  • 1,636
  • 4
  • 23
  • 37
  • 1
    I think you may have to use the old `.then()` syntax to get more than one value. – Barmar Jan 21 '19 at 10:59
  • what exactly you are looking for ..can you please collaborate please., – Ritul Lakhtariya Jan 21 '19 at 11:00
  • `$.ajax (url).always(function (jqXHR) { console.log(jqXHR.status); });` to get status. For more in detail go [here](https://stackoverflow.com/questions/5344145/how-to-get-response-status-code-from-jquery-ajax) – Sudhir Ojha Jan 21 '19 at 11:00
  • If anyone is still looking for the answer, then answer is simple; *Delay the await call*. You can refer to https://stackoverflow.com/a/68231409/15066006 for more details. Basically store the `jqXHR` object from `$.ajax` call, await the object to get response, and once the await is completed, the `jqXHR` object would contain all the details you need – gliesefire Jul 03 '21 at 18:27

0 Answers0