我正在尝试构建一个脚本,其中用户单击提交,并根据表单提交的状态使用JQuery显示消息。我不想使用提醒功能,但是如果它出现的话,我可以这样做。所以我的问题是如何才能使PHP在同一页面上处理表单并根据提交的成功或失败执行我希望它执行的JQuery动画。
这是HTML
<form id="validationformContact">
<div class="col">
<label id="name-label">Name</label>
<input name="Name" placeholder="Enter Name" id="name-input">
</div>
<div class="col">
<label id="email-label">Email </label>
<input name="Email" placeholder="Enter Email" id="emailInput">
</div>
<div class="col">
<label id="phone-label">Phone</label>
<div class="phone-wrapper">
<input name="PhoneOne" placeholder="###" class="phone" id="phone">
<input name="PhoneTwo" placeholder="###" class="phone">
<input name="PhoneThree" placeholder="####" class="phone">
</div>
</div>
<div class="col">
<label id="email-label">Concern </label>
<select name="Concern" placeholder="Type here..." id="concern">
<option>Select Concern....</option>
<option>Safety</option>
<option>Travel</option>
<option>Something else...</option>
</select>
</div>
<div class="col" id="messageCon">
<label id="message-label">Message </label>
<textarea name="textaream" placeholder="Type message here..." id="message"></textarea>
</div>
<br><br>
<input type="submit" value="Submit" id="SubmitButton">
</form>
这是代码 PHP
<?php
$to = "jamell405@gmail.com"; //There email address
$from = $_POST['Email']; //User's email address
$fname = $_POST['Name'];
$phone_one = $_POST['PhoneOne'];
$phone_two = $_POST['PhoneTwo'];
$phone_three = $_POST['PhoneThree'];
$concern = $_POST['Concern'];
$message = $_POST['Message'];
$subject = $fname . " " . "sent you a message!";
$subject2 = "Confirmation of your message!";
$message1 = $fname . " " . "has sent you a message, its contents are below" . "\n" . $message;
$message2 = $fname . " " . "this a confirmation for your message you sent!";
$header = "From:" . $from;
$header2 = "From:" . $to;
mail($to,$subject,$message1,$message);
mail($from,$subject2,$message2);
if(@mail($to,$subject,$message1,$message)) {
echo "<script type='text/javascript'>$('.confirmationContact').slidedown(500);</script>";
}
else {
echo "<script type='text/javascript'>alert('Message failed to send!');</script>";
}
?>
答案 0 :(得分:1)
尝试将json消息返回给jQuery,如下所示:
$arrayResult = array();
if(@mail($to,$subject,$message1,$message)) {
$arrayResult['sent'] = true;
$arrayResult['message'] = 'Message sent successfully!';
echo json_encode($arrayResult);
}
else {
$arrayResult['sent'] = false;
$arrayResult['message'] = 'Some error ocurred, please try again.';
echo json_encode($arrayResult);
}
?>
然后解析它并在jQuery中执行动画,如下所示:
<script>
jQuery(document).ready(function($) {
$.post('myfile.php', {
your:data,
goes:here
}, function(data, textStatus, xhr) {
result = jQuery.parseJSON(data);
if (result.sent == true) {
// your animation goes here
alert(result.message)
}else{
// your animation goes here
alert(result.message)
}
});
});
</script>