Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How retrieve responseJSON property of a jquery $.ajax object [duplicate]

I have this javascript:

$ajax = $.ajax({
    type: 'GET',
    url: 'DBConnect.php',
    data: '',
    dataType: 'json', 
    success: function(data) {},
    error:function (xhr, ajaxOptions, thrownError) {
        dir(thrownError);
        dir(xhr);
        dir(ajaxOptions);
    }
});
console.dir($ajax);
console.dir($ajax.responseJSON);

console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined: enter image description here

like image 246
red888 Avatar asked May 15 '14 14:05

red888


People also ask

Which object can be used to retrieve data in AJAX?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

How get data from AJAX call in jQuery?

ajax({ type: "POST", url: 'test. php', data: {"type":"check"}, success: function(response){ alert(response); } }); There can obviously be more key-val pairs in data. In this case your alert should read: "The type you posted is check".

How does AJAX return an API call?

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


2 Answers

Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.

$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.

like image 55
Yura Avatar answered Sep 18 '22 17:09

Yura


You can use this trick to get the response out:

jQuery.when(
    jQuery.getJSON('DBConnect.php')
).done( function(json) {
    console.log(json);
});

It's late but hopefully will help others.

like image 38
Aria Radmand Avatar answered Sep 18 '22 17:09

Aria Radmand