Im working on a JS shopping cart site and I am trying to send the cart details to mail at the check out function using php mail,here im passing my cart details to php via ajax.
in php when try to send all the cart values using foreach im only able to recive the just last row of cart as foreach is repalcing the previous value
how do i retrive the cart values and send them in a format
js
function SendMail() {
var tableContent = localStorage.getItem('productsInCart');
$.post('read.php', {tableContent: tableContent}, function (data) {
console.log(tableContent);
});
}
php
if (isset($_POST['tableContent'])) {
$tableContent = json_decode($_POST['tableContent']);
foreach ($tableContent as $tableContent) {
$name = ($tableContent->name);
$price = ($tableContent->price);
$quantity = ($tableContent->inCart);
}
$mailTo = "xxxxxxxxxxxxx";
$Subject = " order details ";
$headers = "from :" . $contact;
$txt = "New registration \n Item:" . $name . "\n Quantity:" . $quantity . "\n Price:" . $price . "\n\n\n CUSTOMER DERAILS\n\n Name:" . $contact . "\n Reg No:" . $reg;
mail($mailTo, $Subject, $txt, $headers);
header("location: read.php?mailsend");
}
You're currently overwriting the same variables on each iteration of the loop, which is why they will only contain the last entry.
You should append the values instead, doing something like:
$tableContent = json_decode($_POST['tableContent']);
// Define a variable to store the items in
$items = '';
// Let's add a total sum as well
$total = 0;
// Let's also use different variable names here
foreach ($tableContent as $item) {
// Append to the variable (notice the . before the =)
$items .= 'Item: ' . $item->name . "\n";
$items .= 'Quantity: ' . $item->inCart . "\n";
$items .= 'Price: ' . $item->price . "\n\n";
// Add the price to the total (I'm assuming that the price is an integer)
$total += $tableContent->price;
}
Now when outputting the email body, we have all the items and the total in those variables:
$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;
As you can see, I changed the layout of the mail a bit since the cart seems to be able to contain several items while your email body was written as if only could contain one.
You shouldn't get the cart values, like name and price, from the client in a POST request like this. The client should only send the item id and quantity and then you would fetch the name and price from a database or similar in the backend. Otherwise, anyone can modify the price to be anything they want before it's posted. Never ever trust user data.