tags:

views:

68

answers:

3

I'm having trouble understanding why my code will not work asynchronously.

When running asynchronously the get_price.php always receives the same $_GET value even though the alert before outputs a unique $_GET value.

var arraySize = "<? echo count($_SESSION['items']); ?>"; //get items count
var pos = 0;
var pid;
var qty;

getPriceAjax();
function getPriceAjax()
{
    pid = document.cartItemForm.elements[pos].id;    //product id
    qty = document.cartItemForm.elements[pos].value; //quantity
    alert('Product: ' + pid + ' Quantity: ' + qty);

    $.ajax({
        url:"includes/ajax_php/get_price.php",
        type:"GET",
        data:'pid='+pid+'&qty='+qty,
        async:true,
        cache:false,
        success:function(data){

            while(pos < arraySize)
            {                        
               document.getElementById(pid + 'result').innerHTML=data;
                pos++;
                getPriceAjax();
            }
        }
    })  
}
A: 

I dealt with a similar problem. I can't quite remember what was going on, so this answer may not be too helpful. Your server may be caching the response. Try using POST.

Fletcher Moore
I tried setting type / vars to POST with no luck. Thanks for input.
payling
A: 

Try adding a bit of random number to your get URL so the server doesn't cache it, like so:

url:"includes/ajax_php/get_price.php&rnd=" + Math.floor(Math.random()*10000)

It could also be a timing issue. Since it is asynchronous, it could be stepping through the loop and alerting before the value comes back. Your pos counter won't get incremented until it returns, so you will always be getting the price of pos = 0 until your call comes back. I would move the incrementer outside the success function. Also, try moving the alert inside of the success function.

function getPriceAjax()
{
    pid = document.cartItemForm.elements[pos].id;    //product id
    qty = document.cartItemForm.elements[pos].value; //quantity

    $.ajax({
        url:"includes/ajax_php/get_price.php",
        type:"GET",
        data:'pid='+pid+'&qty='+qty,
        async:true,
        cache:false,
        success:function(data){

            while(pos < arraySize)
            {
                alert('Product: ' + pid + ' Quantity: ' + qty);                        
                document.getElementById(pid + 'result').innerHTML=data;                
                getPriceAjax();
            }
        }
    });
    pos++;
}
manyxcxi
I added rnd to the data fields, no change.
payling
I edited my above answer to show another idea. It could be a timing issue due to async.
manyxcxi
A: 

Recursion almost beat me...

Instead of using a while loop it should have been an if conditional statement.

while(pos < ArraySize) WRONG! - executes the first set of parameters arraySize times.

if(pos < ArraySize) CORRECT! - executes the first, then second, and so on...

payling