Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data, textStatus and jqXHR when calling await jquery.ajax?

I am using JQuery AJAX, using await. I do not want to use the success and error callbacks and I do not want to use the .then syntax.

When calling jquery ajax like so

const { data, textStatus, jqXHR } = await $.ajax(url, {...});

then the variables on the left are not populated.

How to call jquery ajax using await and still get data, textStatus and jqXHR (similar to the success callback)?

(Simply calling const data = await $.ajax(url, {...}); works but I need access to textStatusand jqXHR.)

like image 841
tijoke331 Avatar asked Oct 12 '25 08:10

tijoke331


1 Answers

you can get the 3 parameters you specified in the success option for the ajax function and do the destructuring on that anonymous function

    let data, textStatus, jqXHR;
    await $.ajax(url, {success: (dt, txt, jqx) => {
      data = dt;
      textStatus = txt;
      jqXHR = jqx;
    }});

or extract the function and do it like this

...
const success = (dt, txt, jqx) => {
  data = dt;
  textStatus = txt;
  jqXHR = jqx;
}
...
await $.ajax(url, {success});
...
like image 76
henok Avatar answered Oct 14 '25 04:10

henok