【问题标题】:jQuery If/else statement that adds text to DIV upon successful form submit成功提交表单后将文本添加到 DIV 的 jQuery If/else 语句
【发布时间】:2012-12-07 14:56:31
【问题描述】:

我构建了一个运行良好的表单。但是,当成功提交消息时,用户会被重定向到一个新页面,其中包含我设置的“成功”消息。相反,我希望成功消息显示在表单旁边的 div 中,并在用户想要发送另一条消息时重置表单。同样,我也希望在失败时让我的“错误”消息显示在同一个 div 中。希望有人可以帮助我的 if/else 语句来实现这一点。

这是我的 HTML:

<div id="contact-area">

<form id="theform" name="theform" method="post" action="feedback.php">
<input type="hidden" name='sendflag' value="send">

<p>
<label for="Name">Name:</label>
<input type="text" name="name" id="name" value="" />
</p>

<p>
<label for="Email">Email:</label>
<input type="text" name="email" id="email" value="" />
</p>

<p>
<label for="Message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message"></textarea>
</p>

<p>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</p>

</form>     
</div>

<div class="message">
<p class="submitMessage"></p>
</div>

这是我的 PHP:

<?php

$mail_to_send_to = "myemail@gmail.com";
$your_feedbackmail = "noreply@domain.com";

$sendflag = $_REQUEST['sendflag'];
if ( $sendflag == "send" )
{
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$headers = "From: $name" . "\r\n" . "Reply-To: $email" . "\r\n" ;
$a = mail( $mail_to_send_to, "Feedback form", $message, $headers );
if ($a)
{
print("Message was sent, you can send another one");
} else {
print("Message wasn't sent, please check that you have changed emails in the bottom");
}
}

?>

【问题讨论】:

  • 我建议您查看 ajax 表单和 javascript。这里没有具体的错误,只是“我该怎么做/给我看代码”
  • 我同意阿拉斯泰尔的观点。你想要的并不难,一个 google for ajax jquery 表单会给你数百个教程。此外,如果您卡在实际位上,这里的搜索将提供足够的示例以开始并返回

标签: javascript jquery html forms conditional-statements


【解决方案1】:

如果我正确理解了您的问题,您希望永远不要离开页面,而是根据成功的表单提交来显示或消失 div。如果是这样,看起来您将不得不使用 AJAX。幸运的是,jQuery 内置了这个!我建议如下:

$.post("url.php", { option1: value1, option2: value2 }, function(data) {
    if(data != '')
        $('#theDiv').html("Success!");
});

欲了解更多信息,read up on the documentation here

【讨论】:

    【解决方案2】:

    在此处阅读并遵循示例:jQuery AJAX

    你基本上会做这样的事情。

    $.ajax({
      url: /url/to/your/php,
      data: dataObjectPosting
      success: function(data){
        //the data object will have your PHP response;
        $('#divid').text('success message');
      },
      error: function(){
        alert('failure');
      }
    });
    

    请记住,成功只是意味着 HTTP 200,不一定是您的 PHP 代码如您所见那样成功运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      相关资源
      最近更新 更多