AJAX function doesn't wait for response

Hello Experts,

I'm trying to create a function using AJAX communication. This function loops through several radio button lists to get the selected value in the list. The selected radio buttons' value is sent to the database to get the price of the selected item.
This price is then added to a variable to create a total price of all components. This total price should then be raised with 70 and written to the page.
The problem is that somehow the prices aren't added to the variable so the page always shows 70.

You can see it yourself by following this link: http://www.qualitas-computers.nl/test/amd/budget.php
In this page, click on "Wijzig" on the right side of the page and change one of the selected radio buttons. The price at the bottom should increase but instead it turn into 70.

I hope someone can help me. If you have any questions please post them so i can answer them.

Thanks in advance!
Michael
// Set the combined price of the components
function setPrice()
{
	// Reset the price
	price = 0;
 
	// Create an array filled with the radio buttons
	var componentList = new Array(document.composer.Processor, document.composer.Garantie);
	for (var x = 0; x < componentList.length; x++)
	{
		// Get the next item from the array
		selection = componentList[x];
		for (var i = 0; i < selection.length; i++)
		{
			if (selection[i].checked == true) 
			{
				// Save the value of the selected component
				var id = selection[i].value;
 
				// Call the getXmlHttpObject function
				xmlHttp = getXmlHttpObject();
 
				// Set the URL to the PHP file
				var url = "/test/includes/get_price.php";
				url = url + "?q=" + id;
				url = url + "&sid=" + Math.random();
 
				// Open the get_price file
				xmlHttp.open("GET", url, true);
				xmlHttp.send(null);
 
				// Call the stateChanged function when the server responses
				xmlHttp.onreadystatechange = function()
				{
					if (xmlHttp.readyState == 4)
					{
						// Add the responsetext to the price
						price += parseInt(xmlHttp.responseText);
					}
				}
			}
		}
	}
	// Use innerHTML to write the price
	document.getElementById('price').value = "" + (price + 70);
	document.getElementById('price_basic').innerHTML = "&euro; " + (price + 70) + ",00";
	document.getElementById('price_total').innerHTML = "&euro; " + (price + 82) + ",95";
}

Open in new window

LVL 5
mverschoofAsked:
Who is Participating?
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.

Melih SARICAOwnerCommented:
copy this
document.getElementById('price').value = "" + (price + 70);
        document.getElementById('price_basic').innerHTML = "&euro; " + (price + 70) + ",00";
        document.getElementById('price_total').innerHTML = "&euro; " + (price + 82) + ",95";


if (xmlHttp.readyState == 4)
                                        {
                                                // Add the responsetext to the price
                                                price += parseInt(xmlHttp.responseText);
document.getElementById('price').value = "" + (price + 70);
        document.getElementById('price_basic').innerHTML = "&euro; " + (price + 70) + ",00";
        document.getElementById('price_total').innerHTML = "&euro; " + (price + 82) + ",95";
                                        }

ur request works as async ... be4 ur request completed u do change the cell value..

one one is doing it as i said above..

other is

setting
 xmlHttp.async = false;


after openning  xmlHttp
0
Melih SARICAOwnerCommented:

// Set the combined price of the components
function setPrice()
{
        // Reset the price
        price = 0;
 
        // Create an array filled with the radio buttons
        var componentList = new Array(document.composer.Processor, document.composer.Garantie);
        for (var x = 0; x < componentList.length; x++)
        {
                // Get the next item from the array
                selection = componentList[x];
                for (var i = 0; i < selection.length; i++)
                {
                        if (selection[i].checked == true) 
                        {
                                // Save the value of the selected component
                                var id = selection[i].value;
 
                                // Call the getXmlHttpObject function
                                xmlHttp = getXmlHttpObject();
 
                                // Set the URL to the PHP file
                                var url = "/test/includes/get_price.php";
                                url = url + "?q=" + id;
                                url = url + "&sid=" + Math.random();
 
                                // Open the get_price file
                                xmlHttp.open("GET", url, true);
                                xmlHttp.send(null);
 
                                // Call the stateChanged function when the server responses
                                xmlHttp.onreadystatechange = function()
                                {
                                        if (xmlHttp.readyState == 4)
                                        {
                                                // Add the responsetext to the price
                                                price += parseInt(xmlHttp.responseText);
        document.getElementById('price').value = "" + (price + 70);
        document.getElementById('price_basic').innerHTML = "&euro; " + (price + 70) + ",00";
        document.getElementById('price_total').innerHTML = "&euro; " + (price + 82) + ",95";
                                        }
                                }
                        }
                }
        }
        // Use innerHTML to write the price
 
}

Open in new window

0
mverschoofAuthor Commented:
I've tried your solution but it still doesn't work. If you follow the link http://www.qualitas-computers.nl/test/amd/budget.php and change some of the components it doesn't work properly.

I will try the async option tonight.

Thanks for your effort so far and your quick response!
Cheers, Michael
0
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.

mverschoofAuthor Commented:
The website has been cancelled so i don't need an answer to this question.
It has been a while since any comment was placed so i think it is best if i close the question.
0
dustinbussCommented:
i haven't discovered an elegant solution to making js wait for a response yet, either; though, i'm sure that one is out there.  what i've ended up doing is creating two different functions:


function ajaxFunction () {
   //this functions runs your ajax request and sends the results to a global variable
   window.someResultsVariable = whatever
 
   //then i call function 2 within function 1
   ajaxResultsFunction();
}
 
function ajaxResultsFunction () {
   //check if the results exist
   if (window.someResultsVariable) {
      //do something with the results
 
   //if there are no results set yet, then repeat this second function
   } else {
      setTimeout("ajaxResultsFunction();",200);
   }
}

Open in new window

0

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
mverschoofAuthor Commented:
Just like you said; not the most elegant solution, but it does the trick
0
dustinbussCommented:
if you are going to be running multiple requests on the same page (or the same script more than once), then be sure to delete/unset the global window.whateverResultsVariable.  Otherwise, the ajaxResultsFunction will keep giving you the first result again, when you're expecting a new result.

It's also a good idea to use different global variables for each ajax function that you're running, if you plan on running multiple ajax queries on the same page.  This will prevent two queries from confusing one another and getting their returned results jumbled up.
0
mverschoofAuthor Commented:
Thanks for the tip. I already thought of that but others who will read this question can benefit from it.

Cheers, Michael
0
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
JavaScript

From novice to tech pro — start learning today.