Reputation: 325
I have a select field, #parentCatSelect
whose values get generated via AJAX / PHP after the page loads via the function acLoadParentCategories
.
The function needs to be used two separate ways, first to create a new part (which works fine) and secondly to update a part. When a user updates a part, all the form values (including this one) should be loaded from values in the Database via AJAX. All values load properly, except this one.
I cannot for the life of me figure out why my value is not getting setting after the select values load.
My function to load the categories via ajax:
var acLoadParentCategories = function( callback ) {
var _data = {
action: 'ac_ajax_load_parent_cats'
};
jQuery.post(
the_ajax_script.ajaxurl,
_data,
function( response ) {
var results = JSON.parse(response.results);
var html = '';
for (var i = 0; i < results.length; i++ ) {
html += '<option value="' + results[i].cat_id + '">' + results[i].cat_name + '</option>';
}
jQuery('#parentCatSelect').append(html);
}
);
callback();
return;
};
and where I am to load it, and then properly set the val
acLoadParentCategories( function() {
console.log('happening');
jQuery('#parentCatSelect option[value="1"]').attr('selected', true);
});
The console.log
statement gets called correctly, but no matter what I try, I cannot get the value to set properly after the select box gets generated. What am I doing wrong?
(For clarity, I know that I am manually assigning the value of "1" instead of dynamically loading the ID. I did this just to see if it would work, and still no dice.)
Upvotes: 0
Views: 1300
Reputation: 7074
The problem is because you have addd your callback()
function after $.post
which is async by default. So, your 'callback()' will execute before the ajax complete. You got two options here
$.ajax
sync which I dont suggest.jQuery('#parentCatSelect').append(html);
(success block of $.post
) i.e after your DOM is populated with values.Hope it helps..
Upvotes: 2