How to retrieve HTML and variables with jQuery/Ajax and PHP
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 extern开发者_如何学JAVAal 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.
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");
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?
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.
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.
精彩评论