I have a drop box (Using the jQuery Autocomplete widget) which is populated using an AJAX call to a PHP file called filter items.php
. I want to be able to keep track of what items the user has selected so that if they were to go to another page, their selections are retained when they return.
I'm attempting to accomplish this by populating a table that holds the item's ID's temporarily as they make their selections. When they go back to the page it will make another AJAX call to a PHP file called 'check basket.php' which will return the list of items currently selected. It will then compare items from both lists as it generates the drop down list, when there is a match I add prop('selected', true)
but it does not seem to work?
Here's the code:
//Check for items in Basket
$.ajax({
url: "check basket.php",
dataType: "json",
success: function(datas) {
var s = 0;
var cbox = [];
var itemid = [];
var quant = [];
$.each(datas, function(index, selected) {
while (selected.cbox[s]) {
cbox[s] = selected.cbox[s];
itemid[s] = selected.item_id[s];
quant[s] = selected.quant[s];
s++;
}
})
//BUILD LIST
$.ajax({
url: "filter items.php?type=0",
dataType: "json",
success: function(data) {
$.each(data, function(index, publisher) {
for (r = 1; r < 21; r++) {
j = 1;
while (publisher.item[j]) {
for (sc = 0; sc < cbox.length; sc++) //Compare items in basket to pre-select
{
if (r == cbox[sc] && publisher.item_id[j] == itemid[sc]) {
alert(publisher.item[j] + " is in Basket for cbox " + cbox[sc] + " and J is " + j);
$('#' + r + 'combobox').append($('<option>', {
value: publisher.item_id[j]
}).text(publisher.item[j]).prop('selected', true));
} else
$('#' + r + 'combobox').append($('<option>', {
value: publisher.item_id[j]
}).text(publisher.item[j]));
j++;
}
}
}
})
}
});
}
});
I've realised what I've done wrong here, Prop('selected',true) is working fine, its just that the actual content of the list was not generated before the Jquery autocomplete code did its thing. I changed the the setting of the AJAX functions that generate the list to be Asynchronous and that did the trick!