I have an exam (tomorrow) that covers html, javascript, ajax, php, mysql and apache. I have been going over previous exams and one of the q's is to write the code for a program that displays an order form, but I am stuck on is the Ajax to keep the total (prices) box updated as amounts of products are ordered.
I have it working, but only if an amount is typed in once. In my solution if someone goes and changes an amount (say from 1 to 3) then it will add the price of 3 more of that product obviously not an ideal solution. I realise that a loop needs to be added, but after many hours of trying I can't get it to work properly. I realise this exact problem won't be in the exam but I would like to get my head around it as there will be something similar.
In the actual html code the form is created dynamically, according to what is in the database. The text box is generated with the id of the product as the text box id and the name is amt[] so that these can be sent to getTotal.php to work out the cost.
Here is the javascript/ajax that is activated on the onchange of textbox:
function getAmt(txtBox){ //in solution won't need to use this text box
var xhr = new XMLHttpRequest();
var id = txtBox.id; //id from the textbox - in solution won't need these two
var amt = txtBox.val; //value that has been typed into the textbox
var total = document.getElementById("total").value; //get current total value
xhr.onreadystate = function(){
if(xhr.readyState==4 && xhr.status == 200)
{
var result = xhr.responseText;
document.getElementById("total").value = result;//place new total in form
}
}
xhr.open("GET", "getTotal.php?amt="+amt+"&id="+id+"&tot="+tot);
xht.send(null);
}
To get what I want, which is instead of using the current total and only the current text box, is that everytime there is a change to process each text box and overwrite the total with a new total. To do this I don't have the pass the txtBox value as I need to loop through all of the id's & values from amt[]
This code does that:
var arrayAmt = document.getElementsByName("amt[]");
var id;
var amt;
for(i=0; i<arrayAmt.length; i++)
{
id = arrayAmt[i].id;
amt = arrayAmt[i].value;
}
I am just stumped of where to put the for loop, or what part of the ajax call goes inside the loop.
I tried many different formats yesterday, and lost lots of study time.
I would really appreciate any suggestions on how to make this work
(can't use anything else such as jQuery)
Cheers