0
var getTemplateCall = $.ajax({
    url: url,
    type: type,
    data: data
});
console.log(getTemplateCall);

This code will show me a break down of the ajax response in the console including 'responseText' property and its contents.

I want to access just the response text as a variable so I have tried

console.log(getTemplateCall.responseText);
console.log(getTemplateCall['responseText']);

These both returned 'undefined' when what I actually want to see is the contents of the responseText property. I think this is a syntax problem.

What is the correct way to access the responseText?

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
David H
  • 71
  • 8
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille Jan 24 '18 at 12:44

2 Answers2

1

getTemplateCall does not contain the result of your async query. It contains your async query. Use getTemplateCall.done(...)

From the official jQuery documentation :

var getTemplateCall = $.ajax({
    url: url,
    type: type,
    data: data
});

getTemplateCall.done( data => { // This is the callback of your asynchronous call
     console.log(data);
})

or just :

$.ajax({
        url: url,
        type: type,
        data: data
    }).done( data => {
         console.log(data);
    })
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
1

do not write it together,execute:

var getTemplateCall = $.ajax({
    url: url,
    type: type,
    data: data
});

after one second,execute:

console.log(getTemplateCall.responseText);

if you write it together,you will get undefined because the browser is sending the ajax-request.So,you have to wait for a second. actually the native code is like this:

var xhr=new new XMLHttpRequest();
xhr.open(url, 'get');
xhr.onreadystatechange=function () {
    // the readystate is changing,when the readystate===4
    // the request is done,then ,we can get the data
    //do something
};
xhr.send();
xianshenglu
  • 4,943
  • 3
  • 17
  • 34