Since AJAX calls are asynchronous by default, you need to move your value assignment to run after the code that populates your select
. Otherwise the value assignment occurs before the response comes back.
I assume whatever code populates the select
is set up to run after the response is received. So placing your value selection after that code should solve the issue.
(In other words, it will go inside the populateOptions()
function.)
Beyond that, it is tough to offer a solution without seeing your code.
EDIT: Here are a few examples of how this could work. Any one of these will be better than setting async: false
in the request.
You can place the code that needs to wait for the response inside the success:
callback.
function populateOptions() {
$.ajax({
url: "some/path",
success: function( resp ) {
// Place ANY code that needs to wait for the response in here.
// This way it will not run until the successful response is received.
}
});
}
Or you could place the code that needs to wait for the response inside another function, and call that function from inside the success:
callback.
function populateOptions() {
$.ajax({
url: "some/path",
success: function( resp ) {
// Call this function when the successful response is received.
successFunction( resp );
}
});
}
function successFunction( resp ) {
// Place ANY code that needs to wait for the response in here.
}
Or, say if populateOptions()
should be reused in different ways, so you need a different callback, you can pass a function in from another function that will be called inside the success:
callback.
function myMethod() {
// Send a function as an argument when you call populateOptions()
populateOptions( function(resp){alert(resp);} );
// Code that does NOT need to wait can still go here
}
function populateOptions( callback_fn ) { // Receive the function that was sent
$.ajax({
url: "some/path",
success: function( resp ) {
// Call the function that was sent
callback_fn( resp );
}
});
}
Or taking the same example as above, you could actually use the function you passed in as the success:
callback.
function myMethod() {
// Send a function as an argument when you call populateOptions()
populateOptions( function(resp){alert(resp);} );
// Code that does NOT need to wait can still go here
}
function populateOptions( callback_fn ) { // Receive the function that was sent
$.ajax({
url: "some/path",
success: callback_fn( resp ) // Now the function passed is the callback
});
}