Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences populating an associative array through $.ajax and $.get/$.post

I tried to populate the global var selectedDates thought the first function but it fails when I try to get some value, as for example, selectedDates['1/23/2013']

After try with $.ajax instead $.get I can obtain values like selectedDates['1/23/2013'].

Where is the difference if both of them populates an outer var the_selected_dates which is returned to set selectedDates?

var selectedDates = {};

function using $.get fails:

function getSelectedDates_fails(lead_id, month) {
    var the_selected_dates = {};
    $.get(
            window.location.href,
            {
                gf_lm_ajax : 1,
                get : 'lead_reminder_get_dates',
                lead_id : lead_id,
                month : month,
                nonce_gf_lm_ajax : gf_lmJsVars.nonce_gf_lm_ajax

            },
    function(output) {
        $.each(output.reminders, function(n, val) {
            the_selected_dates[val.date] = val.date;
        });
    }, 'json');
    return the_selected_dates;
}
selectedDates = getSelectedDates_fails(35, 12); console.debug(selectedDates);

debug data

enter image description here

enter image description here

function using $.ajax works:

function getSelectedDates_works(lead_id, month) {
    var the_selected_dates = {};
    $.ajax(
            {
                url : window.location.href,
                dataType : 'json',
                data : {
                    gf_lm_ajax : 1,
                    get : 'lead_reminder_get_dates',
                    lead_id : lead_id,
                    month : month,
                    nonce_gf_lm_ajax : gf_lmJsVars.nonce_gf_lm_ajax
                },
                async : false,
                success : function(output)
                {
                    $.each(output.reminders, function(n, val) {
                        the_selected_dates[val.date] = val.date;
                    });
                }
            });
    return the_selected_dates;
}
selectedDates = getSelectedDates_works(35, 12); console.debug(selectedDates);

debug data

enter image description hereenter image description here

like image 545
Igor Parra Avatar asked Dec 26 '22 13:12

Igor Parra


1 Answers

While you are running $.ajax synchronously, $.get is not.

That's why getSelectedDates_fails() returns faster than you are getting a response from the server hence returning an empty object, {}.

What you are seeing in selectedDates is the state of the object before the request is completed asynchronously.


You can use $.ajaxSetup() to globally change the behavior of all $.ajax calls. But, I wouldn't recommend it for setting async to false.

like image 158
Alexander Avatar answered Apr 06 '23 00:04

Alexander