首页 > 解决方案 > 通过 php mail -ajax 发送购物车详细信息

问题描述

我在一个 JS 购物车网站上工作,我正在尝试使用 php 邮件在结帐功能处将购物车详细信息发送到邮件,这里我通过 ajax 将我的购物车详细信息传递给 php。

在 php 中,当尝试使用 foreach 发送所有购物车值时,我只能接收最后一行购物车,因为 foreach 正在替换先前的值

我如何检索购物车值并以某种格式发送它们

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");
}

标签: javascriptphpajaxemailcart

解决方案


您当前在循环的每次迭代中都覆盖了相同的变量,这就是它们只包含最后一个条目的原因。

您应该改为附加值,执行以下操作:

$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;
}

现在,当输出电子邮件正文时,我们在这些变量中有所有项目和总数:

$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;

正如您所看到的,我稍微更改了邮件的布局,因为购物车似乎能够包含多个项目,而您的电子邮件正文被写成好像只能包含一个。

关于这种方法的警告

您不应该在这样的 POST 请求中从客户端获取购物车值,例如名称和价格。客户端应该只发送商品 ID 和数量,然后您将从数据库或后端的类似数据库中获取名称和价格。否则,任何人都可以在发布之前将价格修改为他们想要的任何东西。永远不要相信用户数据。


推荐阅读