21

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

red888
  • 27,709
  • 55
  • 204
  • 392
  • Is there a specific reason you need it, over what is provided to the `success` handler (which is the responseJSON anyway) – Rory McCrossan May 15 '14 at 14:31
  • This will be undefined/empty until the ajax call (which is asynchronous) is completed. At that point you have access to it from the success method.. – Gabriele Petrioli May 15 '14 at 14:32
  • 1
    How do I get the response data out of the success callback? – red888 May 15 '14 at 14:37
  • 2
    @user1028270: You can't. AJAX is *asynchronous*. You can only access the data from the callbacks. What you can do is use `.done()` to add another callback so you can access the JSON `$ajax.done(function(data){ console.log(data); });`. – gen_Eric May 15 '14 at 16:25
  • Please review my answer - you can if you set `async` to false and go from there ;-) – Stan Smulders Dec 13 '15 at 20:09

4 Answers4

23

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.

Yura
  • 2,690
  • 26
  • 32
9

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.

Aria Radmand
  • 321
  • 2
  • 8
0

The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.

For example:

success: function(data) {
 alert(data[0]);
},

If you want this response, out of the success, you can set a variable outside, and try this:

success: function(data) {
 myVar = data;
},

Hope, this help.

Ferchi
  • 100
  • 1
  • 9
  • Yes, but how do I get it out of the success callback? I want to work with the data in another location in my script. – red888 May 15 '14 at 14:45
  • Hello, set a variable outside the ajax function, and in the success, asign the value of data, to this variable, so you can use this data in another location. – Ferchi May 22 '14 at 16:05
-2

For those who don't really mind if it's synchronous, like I was, you can do this:

$('#submit').click(function (event) {
    event.preventDefault();

    var data = $.ajax({
        type: 'POST',
        url: '/form',
        async: false,
        dataType: "json",
        data: $(form).serialize(),
        success: function (data) {
            return data;
        },
        error: function (xhr, type, exception) {
            // Do your thing
        }
    });

    if(data.status === 200)
    {
        $('#container').html(data.responseJSON.the_key_you_want);
    }
});

It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.

Edit the options to match your situation. Happy coding :)

TheLaj
  • 3
  • 4
Stan Smulders
  • 6,079
  • 1
  • 27
  • 23
  • 2
    The synchronous solution is almost always the wrong one. – HumbleWebDev Jun 22 '17 at 21:26
  • Yes, it's bad practice to use synchronous solutions for most use cases here. But +1 for being the only person to provide a complete working example answer. I think sometimes there's value in seeing how the synchronous examples work clearly, too. – thclark Dec 20 '17 at 11:45
  • I just read comments saying that sync is bad practice but nobody explains why, if the option exists is because there are situations where is needed – rome3ro May 02 '21 at 20:34