Alright, I have been breaking my head over this one for more than a day now. And I’m sure it’s very simple to solve.
The function below is supposed to do this: get some post data from a php file (xml format returned), on success process that data to check if an item in the cart already exists with this item, to prevent it from being added twice under the same name. So it loops through the current list of items and finds a match. If it’s not found, it will add the item just fine. If it is there, a manipulation needs to take place to update that row with the new amount.
For some strange reason I can’t get the code to execute as soon as there is a match. if(match == true) just doesn’t do anything, even though console.log("index found present status: "+match); returns true in the console just fine a few lines above that.
So how is this possible? Does it have to do with scope or something?
The if(basket.fnGetData().length == 1) addToCart('window', 1); is only there to make sure the second call of the function there is a duplicate item that needs to be ‘merged’ into one. Saves me clicking on stuff on the website every time.
function addToCart (ueid, amount)
{
// you can remove the follow alert() call, typically this function would
// scroll (through an #anchor or maybe tween/scroll with jQuery) down to
// the area below the panorama tour and there display the user-interface
// for buying/sponsoring items
console.log("buy "+ueid+" "+amount+" times");
var match = false;
console.log("before ajax present status: "+match); //output: false
//Get detailed info about this item
iteminfo = jQuery.ajax(iteminfourl, { data: { "ueid": ueid }, type: "POST",
success:
function(data)
{
console.log("ajax success present status: "+match); //output: false
totalprice = (amount * $(data).find('price').text());
//first check if the item already exists in the table
currentContents = basket.fnGetData();
if(currentContents.length > 0)
{
for(index = 0; index <= currentContents.length; index++)
{
if(currentContents[index][0] == ueid)
{
console.log("ueid and index are the same");
match = true;
var updateIndex = index;
console.log("index found present status: "+match); //output: true
}
}
}
if(match == true)
{
//this never gets executed, even if match is set to true.
//also console.logs just before the if statement are only
//executed when match = false all the way...
console.log("item is present, update index "+updateIndex);
//basket.fnUpdate()
}
else
{
basket.fnAddData(
[
ueid,
amount,
totalprice,
'X'
]
);
if(basket.fnGetData().length == 1)
addToCart('window', 1);
}
}
});
}
should be
The key being use
<instead of<=in the loop expression.I think your loop is running an extra time and throwing a TypeError when you do
currentContents[1 too many][0]. Look at the debug console for error warnings being printed out.