-2

I have some thing like this:

$.ajax({
    type: 'GET',
    url: my_url,
    success: function(data) {

        $('#some_div').data('test', 'This is a test');

    }
});

Then outside of the success callback, I tried to access my test variable like

console.debug($('#some_div').data('test'));

But this returns undefined

Any help please

Thank you

user765368
  • 19,590
  • 27
  • 96
  • 167

3 Answers3

0

You need to familiar yourself with the $.ajax .done() and .fail() methods.

jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

More Info Here!

DevlshOne
  • 8,357
  • 1
  • 29
  • 37
0

The success function happens AFTER the request returns successfully.

Your console.debug line happens immediately after you make the $.ajax call, i.e. before the value it's inspecting gets set by the ajax success callback:

  1. $('#some_div').data('test') is undefined
  2. ajax call is made
  3. $('#some_div').data('test') is still undefined!
  4. Your console.debug line runs
  5. $('#some_div').data('test') is still undefined...
  6. Your ajax call returns sucessfully; $('#some_div').data('test') gets defined now

Yes, this is the most simple example of how asynchronous logic works, hence the comments you're getting.

tuff
  • 4,895
  • 6
  • 26
  • 43
0

You'll need to store the result in a global variable, i.e:

var globalVariable;
$.ajax({
    type: 'GET',
    url: my_url,
    success: function(data) {

        $('#some_div').data('test', 'This is a test');
        globalVariable = data;
    }
});

Storing things in the global scope isn't the best idea, so I'd recommend wrapping it in a Self-Executing Anonymous Function to avoid poluting the global scope.

(Note: there are better ways of doing it, but avoiding complicating it too much)

Ashley
  • 1,459
  • 2
  • 12
  • 25
  • `$('#some_div').data('test', 'This is a test');` is globally available. – Kevin B Aug 26 '13 at 17:41
  • @KevinB But the data that's returned to the success function is not. – Ashley Aug 26 '13 at 17:59
  • right... he's using 'this is a test' as a test. he's obviously passing `data` there instead in reality. – Kevin B Aug 26 '13 at 18:02
  • My point is there's nothing wrong with how he's currently storing the data. The problem is *when* he is accessing the data, which your answer doesn't address. – Kevin B Aug 26 '13 at 18:04