【问题标题】:How can I show the PHP results of a contact form with AJAX?如何使用 AJAX 显示联系表单的 PHP 结果?
【发布时间】:2013-03-26 14:55:49
【问题描述】:

我有一个简单的 html 联系表格,以及用于发送电子邮件的 php 脚本。它工作得很好,但我希望结果(电子邮件已发送......)显示在同一页面中,而不更改页面。我该怎么做?

HTML:

<form name="contact" action="includes/send.php" id="contact_form">

    <input type="text" placeholder="Name" name="name" /> <br />

    <input type="email" placeholder="Email Address" name="email" /> <br />

    <textarea name="message" placeholder="Message" rows="8"></textarea> <br />

    <input type="submit" name="submit" id="submit_btn" value="Send" /> 

</form>

PHP:

<?php

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = 'amar123syla@gmail.com';
$subject = 'Message from AMARSYLA.COM';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: amar123syla@gmail.com';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
    mail($to, $subject, $message) or die('Error sending Mail'); //This method sends the mail.
    echo "Your email was sent!"; // success message
}

?>

【问题讨论】:

  • 您似乎在要求 Ajax 101 教程。这不是适合 Stackoverflow 的问题。请尝试使用搜索引擎(它可能会为您提供this mdn resource 等结果)。
  • 如果你只想这样做,你不必使用ajax,除非你不希望页面在提交表单时刷新。

标签: php html ajax load


【解决方案1】:

在这里看看这是否有效:

<form name="contact" action="**submit to same page**" id="contact_form">



<input type="submit" name="submit" id="submit_btn" value="Send" /> 

</form>

然后对于 php(与电子邮件表单在同一页面上)只需添加 if submit

<?php
if(isset($_POST['submit'])){

 run your email script, add javascript, etc.
echo "Your email was sent!"; // success message
}


  }
    ?>

【讨论】:

    【解决方案2】:
    jQuery.post('email.php', score, function(result) {
        jQuery('#textBlock').html(result);
    });
    

    类似的东西应该可以工作(在这种情况下,结果是你的 php 中的回显)

    一种首选方法是将您的 php 结果编码为 json,这样您就可以在 Javascript 中对其进行更多控制。

    jQuery.post('email.php', score, function(result) {
        if (result.result == true) {
            jQuery('#textBlock').html(result.text);
        }
    });
    

    在 email.php 中:

    $result['result'] = true;
    $result['text'] = 'Message has been sent';
    
    header('Content-Type: application/json');
    echo json_encode($result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多