views:

1323

answers:

4

I have an HTML form which uses selections from a drop-down list to populate a mySQL table, but with jQuery / AJAX calling an external php file to update the display of entered lines below the original form.

The purpose of the form is an order entry system, and as such works: select an item, see it added to the list. The problem that I have is that as well as having the entered items displayed, I want to show the total order value updating. I thought that I would be able to use a PHP session variable, but that doesn't seem to work unless the original page is refreshed.

Therefore, my question is: is there a way to get session variables (or any other sort of variable) back from my external php file as well as the HTML that I am appending to the displayed page?

If it helps this is the code that I'm using to call the external php when adding a new row:

$.ajax({
type: "POST",
url: "ajaxInsertOrderLine.php",
data: dataString,
cache: false,
success: function(html){
 $("#orderItems").append(html);
 document.getElementById('inputStockNo').value='';
 document.getElementById('qty').value='';
 document.getElementById('totalAmount').value="<?php echo $_SESSION["totalValue"]; ?>";
}});

where "ajaxInsertOrderLine.php" is the external file, 'inputStockNo' and 'qty' are two form variables being sent to the script and zeroed after a successful insertion.

+2  A: 

you could return a Json object (maybe using getJSON) containing the two different variables you want to retrieve, one being the html to append and ther other being the total order value.

seengee
+3  A: 

You can pass many values back to your jQuery script in the form of an array. For instance, I could pass the following:

session_start(); // necessary for getting/setting SESSION data
print json_encode(array(
  "username" => $_SESSION["username"],
  "msgCount" => 0,
  "userHTML" => "<p>There are no new messages</p>";
));

Then from your jQuery code, you'll use the JSON method of data-retrieval:

$.post("page.php", {}, function(results) {
  alert(results.username + " has " + results.msgCount + " messages.");
  $("messages").append(results.userHTML);
}, "json");
Jonathan Sampson
+2  A: 

Why not just scrap the session variable idea - do the total order value calculation on the server in the php page and just send back the value along with item you're adding to the list?

Steerpike
I can do that; as I'm returning an HTML table row, I can include it in a table cell on the end of the row. The problem is that I then have a running total beside each line when I want just one total showing somewhere on the page that updates as a new row is added.I'm already doing the calculation on the server; I just can't work out how to get the result back to the original page in a way I can use.
AndrewDFrazier
A: 

I found a script here: Javascript Session Variables which does what I want, and may help anybody else who is looking to use session variables with AJAX.

AndrewDFrazier