【问题标题】:Unable to store value of a variable using AJAX in PHP无法在 PHP 中使用 AJAX 存储变量的值
【发布时间】:2015-09-27 08:01:43
【问题描述】:

这是我的 html 表单。从这里我将 3 个值传递给我的 ajax

<div class="form-container">
     <h3>Drop me a line</h3>
     <p id="response"></p>
     <form role="form" id="form">
<div class="form-group">
     <input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
<div class="form-group">
    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="form-group">
    <textarea rows="4" class="form-control" cols="50" id="message1" name="message" placeholder="Message"></textarea>
 </div>
 <button type="submit" id="email-button" class="btn btn-danger btn-contact">Submit</button>
 </form>
 </div>   

这里我使用 Ajax 发送电子邮件。从这里我可以成功传递所有这三个参数。我通过调试检查了 chrome。我得到了所有 3 个值。

这是我的 AJAX 调用。

$(document).ready(function(){
     $('#email-button').click(function() {
           name = $('#name').val();
           email = $('#email').val();
           message2 = $('#message1').val();
            $.ajax({
                    type: "POST",
                    url: "email.php",
                    data: "name=" + name + "email=" + email + "message3=" + message2,

                     success: function (html) {
                     if (html == "true") {
                       $('#form').remove();
                       $('#response').html("<p>Thank you for your message. I'll get back to you ASAP </p>");
                     }
                     else {
                       $('#form').remove();
                       $('#response').html("<p> Something Wrong </p>");

                     }
                     }
                    });
                       return false;

                    });
                    });

但在我的 PHP 代码中,我无法在 $message 变量中存储任何内容。它不在此变量中存储任何值。我尝试使用 echo $message 但它显示的是空字符串。

这是我的 email.php 文件

 <?php
    if(isset($_POST['name'])) {
      $name = addslashes(strip_tags($_POST['name']));
    }
    if(isset($_POST['email'])) {
      $email = addslashes(strip_tags($_POST['email']));
    }
    if(isset($_POST['message3'])) {
      $message = addslashes(strip_tags($_POST['message3']));
    }

      $header = "Name:" . $name . "Email:" . $email ;
      $to = "xyz@gmail.com";
      $subject = "From My website";

      mail($to, $subject, $message, $header);
      echo "true";
   ?>

即使在邮件中,我也只能收到主题。不是标题也不是消息。我找不到我的错误。我通过 echo $header 获取姓名和电子邮件;但使用相同的语法我看不到 $message。它只给我空字符串。

【问题讨论】:

  • 那么 $_POST 包含什么?

标签: php html ajax


【解决方案1】:

这样试试

data:{"name":  name,  "email" : email,  "message3" : message2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    相关资源
    最近更新 更多