Vitalii Ponomar
Vitalii Ponomar

Reputation: 10936

jQuery: how to refresh javascript value on select event?

I have such code:

var regions = [{'label': 'array', 'value': '1'}];   //default values

$("#auto1").select({
    regions = jQuery.parseJSON(     //updating process
        $.ajax({
            type: 'POST',
            url: '/ajax/place/',
            data: { country: value }
        })
    );
    return false;
});

$("#auto2").some_func({
    initialValues: regions,     //here must be updated values, but it's not
});

I think it is understandable from above code: when page loaded, element #auto2 has default values, but when I select smth from #auto1 it must be updated, but it's not.

How can I update the values corresponding to data value.

Thanks!

Upvotes: 0

Views: 385

Answers (2)

Keith.Abramo
Keith.Abramo

Reputation: 6955

Your problem is with how you are trying to get your ajax data back. ajax calls are asyncrynous, which means they will not hold up the code until they return. Because of this jQuery.ajax allows for you to tie into success and failure callbacks which fire depending on if the ajax response returned a success or failure code. You need to parse your data in the success callback and store it in a variable at a scope where your some_func method can see it

var regions = [{'label': 'array', 'value': '1'}];   //default values

$("#auto1").select({
        $.ajax({
            type: 'POST',
            url: '/ajax/place/',
            data: { country: value },
            success: function(data){
              regions = jQuery.parseJSON(data);
            }
        });
    return false;
});

$("#auto2").some_func({
    initialValues: regions 
});

Upvotes: 0

Oyeme
Oyeme

Reputation: 11225

$("#auto1").select({
    regions = jQuery.parseJSON(     //updating process
        $.ajax({
            type: 'POST',
            url: '/ajax/place/',
            data: { country: value },
            success: function( data ) {
               //trying yo update values, after successfull response
               //some cool code is here or calling a function to update values
            },
            error: function( data ) {
               //error to update
            }
         }
        })
    );
    return false;
}); 

Upvotes: 3

Related Questions