0

I have a charts being drawn using javascript. Now when I call ajax and call the initialize chart function, it won't update the the charts. So I want to be able update the global variable I have. I can't find any example of how I might be able to achieve this. When i look at response text, the script section seems to have the updated value.

var num_accounts = 0

$(document).ready(function() {
    var form = $('.accounts');
    form.ajaxForm({
        success: function(response){
            data = $.parseHTML(response);
            $('.stats').html($(data).find('.stats').html());
            $('#account-body').html($(data).find('#account-body').html());
            // THIS IS WHAT I WANT TO BE ABLE TO DO 
            num_accounts = $(data).find('num_accounts').val();
            initialize_charts();
            makeClickable();
        },
        error: function(xhr, errmsg, err){
            $('#results').html("<div class='alert-box alert radius' data-alert>"+
            "Oops! We have encountered an error. <a href='#' class='close'>&times;</a></div>");
            console.log(xhr.status + ": " + xhr.responseText);
        }
    });

    $('.ui-check').change(function(){
        $(form).submit();
    });

    $('.range')
      .change( function () {
        $(form).submit()
      })
    .keyup( function () {
        $(this).change();
    });
});
rak1n
  • 671
  • 1
  • 8
  • 17
  • [How to return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/1529630) – Oriol Aug 10 '15 at 17:26

1 Answers1

0

It's asynchronous, so the global variable will be updated, but not precisely within the same tick of the event loop as all other synchronous function calls. In other words, synchronous actions that do not happen as a result of the XHR response will conceptually "ignore" any changes.

In other words, everything you want to do with the response needs to happen inside the success callback. That's just how async stuff works.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68