Waiting to all ajax requests have finsihed

My code below gets the quantity of each item and if 1 or more it executes the php code to add a row into my table. I then have a page redirect at the bottom. However the redirect must happen before all the items are added into the database as say I have 20 rows have items only 11 get added. Why is this and what am I doing wrong?

$( ".ListResults .quantity" ).each( function(index) {
		var value2 = $(this).val();
		if(!isNaN(parseInt(value2))) {
			var quantity = parseInt(value2);
			if(quantity > 0) {
				var tr = $(this).closest('tr');
				var thecode = $(tr).find('.code').html();
				var theprice = $(tr).find('.theprice').html();

				$.post("addtocart.php", {
									code: thecode,
									cust_id: $( "#cust_id" ).html(),
									price: theprice,
									quantity: quantity
        						}, function(data) {  
									
                            	});
								
			}
		}
	});

		
		$('.loadingDiv').hide();
		window.location.href = "/cart";
			

Open in new window

petewinterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
Besides making it harder to control, you're going to sink the server in no time with this approach.

You should do one single POST call to the server with all the items, passing a collection of items instead of each item one by one like you're doing now.

Doing so will ease the traffic on the wire and will be much easier to manage by simply catching the success of that single POST.
It will also be possible to catch exceptions properly because as you have it now, if one of the POST requests fail, what will you do?

Your code should be changed to look like the following:
var items = [],
    custId = $("#cust_id").text(); // avoid selecting the DOM multiple times for the same value

$(".ListResults .quantity").each(function (index) {
    var value2 = $(this).val();
    if (!isNaN(parseInt(value2))) {
        var quantity = parseInt(value2);
        if (quantity > 0) {
            var tr = $(this).closest('tr');
            var thecode = $(tr).find('.code').html();
            var theprice = $(tr).find('.theprice').html();

            items.push({
                code: thecode,
                cust_id: custId,
                price: theprice,
                quantity: quantity
            });

        }
    }
});

// post everything at once
$.post("addtocart.php",
		items,
		function (data) {
			$('.loadingDiv').hide();
			window.location.href = "/cart";
		}
);

Open in new window

petewinterAuthor Commented:
Thanks for the advice. Could you please show me an example of the best way to do what you recommend? Would I get the info for each row and store in an array, then post?
Alexandre SimõesManager / Technology SpecialistCommented:
I edited my comment meanwhile, you'll find the code there.

No, you'll receive a single response for the whole request. It's to you to set what response that will be. If you want you can specify which item has an error but be aware that the whole request itself might fail due to network issues for instance.

Also make sure that you DB instruction that saves this data is performed inside a transaction. Probably you want to rollback everything if one row fails otherwise it will be harder to maintain when the user resubmits the same request.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

petewinterAuthor Commented:
Thanks for the example. Are you able able to help me with how I output the "items" array in the php? I need to add a row into my mysql database for each item.
Alexandre SimõesManager / Technology SpecialistCommented:
I'm not a PHP guy but I think you can do something like:
// post everything at once
$.post("addtocart.php",
		{data: JSON.stringify(items)},
		function (data) {
			$('.loadingDiv').hide();
			window.location.href = "/cart";
		}
);

Open in new window

In your PHP

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

Open in new window

This was based on a piece of code found here:
http://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
petewinterAuthor Commented:
Many thanks again. I know you said your not a php guy, but I am getting the error below...

Warning: Invalid argument supplied for foreach()

Any idea's?
Alexandre SimõesManager / Technology SpecialistCommented:
Notice that I've changed the ajax call itself to start passing the data as:
{data: JSON.stringify(items)}

did you apply this change?

Anyway, I'm not sure if this works like this.
Probably I'm just saying garbage on this PHP part.

I'm sure Ray_Paseurcould be a much better help on this regard.
Try dropping him a message or add PHP to your tags.
petewinterAuthor Commented:
Many thanks Alexandre. Yes I did pass the data as {data: JSON.stringify(items)} . I will wait for Ray on the php.

Really appreciate your help.
petewinterAuthor Commented:
Correction to my earlier error message. I did do something else wrong, but now I am getting the below error message...

Catchable fatal error: Object of class stdClass could not be converted to string in /home/xxxx/public_html/orderpad/addtocart-test.php on line 8

Line 8 is  echo $d;
petewinterAuthor Commented:
When I dump the array I get...

array(3) { [0]=> object(stdClass)#1 (4) { ["code"]=> string(6) "R64072" ["cust_id"]=> string(2) "32" ["price"]=> string(5) "84.20" ["quantity"]=> int(2) } [1]=> object(stdClass)#2 (4) { ["code"]=> string(6) "R64075" ["cust_id"]=> string(2) "32" ["price"]=> string(5) "76.97" ["quantity"]=> int(1) } [2]=> object(stdClass)#3 (4) { ["code"]=> string(10) "CMY-E4J48A" ["cust_id"]=> string(2) "32" ["price"]=> string(5) "79.43" ["quantity"]=> int(3) } }

Open in new window

Alexandre SimõesManager / Technology SpecialistCommented:
Can you post your PHP code?
petewinterAuthor Commented:
It's exactly the same as your code...

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

Open in new window

petewinterAuthor Commented:
Many thanks for your help.

I resolved the last part with this link: https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
Alexandre SimõesManager / Technology SpecialistCommented:
You're welcome mate, glad you managed to find your way through.

Sorry I couldn't help you more.

Cheers!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.