我有一个表单,它用HTML定位在页面上,如果用户填写了表单,那么他们会得到PHP消息的感谢。因为表单是用<form id="formIn">
CSS定位的,所以PHP文本现在处于错误的位置,有没有人知道如何定位它,以便PHP回显文本嵌套在表单上?我试图在 PHP 中包含代码,即
<div id='"text'">
但没有快乐。
到目前为止使用的代码是:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."'n".$contact_text;
$headers = 'From: '.$contact_email;
if (@mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
执行此操作的一个好方法是创建一个div 以在表单页面中显示消息,并从 php 脚本返回到表单页面,包括对 url 的form.html?error=email
或form.html?success
。 然后使用javascript,您可以识别何时发生这种情况并显示一条消息或其他消息。
如果需要一些代码示例,请注释。
编辑:假设您的 php 脚本检测到电子邮件字段未填充,因此它将返回到表单网页,并在 url 中包含一个变量:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
然后,在您的表单网页中,您必须添加一些 javascript 来捕获 URL 中的变量并在页面中显示一条消息:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
在这种方法中,我们有data[0]
是 var 名称,data[1]
是 var 数据。 您应该像这样实现该方法:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
最后,为了显示消息,我建议使用HTML和CSS创建一个div,并使用jQuery对其进行动画处理以显示和消失。或者只是显示警报alert("Email Error");
只需在表单之前或之后创建一个<div>
,并在上面放置 IF SUBMIT 条件。喜欢
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>