Ajax 联系表示例:(最初是荷兰语,有点旧且编码错误)
请记住,此示例需要 jquery。只需从他们的网站下载 jquery.js 并将其添加到 HTML 中的脚本中
表单.html
<form id="frm_contact" name="contactformulier">
<label>Naam<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="naam" />
<br/><br/>
<label>Bedrijf</label><br/>
<input type="text" size="15" maxlength="50" name="bedrijf" />
<br/><br/>
<label>Email<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="tmail" />
<br/><br/>
<label>Bericht<span style="color:red">*</span></label><br/>
<textarea name="tekst">
</textarea>
<br/><br/>
(<span style="color:red">*</span>) Required fields!
<br/><br/>
<div id="subbutton">Send</div>
</form>
<div id="error-msg"></div>
form.html (javascript 代码)
<script>
$(document).ready(function(){
var err="";
$("#subbut").click(function(){
$.post("PHP/ajax_contact.php", $("#frm_contact").serialize(),
function(data){
switch(data){
case '0':
err="<span><center>Thanks for contacting us!</center></span>";
$("#frm_contact").hide();
break;
case '1':
err="Invalid email!";
break;
case '2':
err="Fill in all fields please!";
break;
case '3':
err="Error sending this mail.";
break;
default:
err="<center>Mail server is offline.</center>"; //Or whatever error
$("#frm_contact").hide();
}
$("#error-msg").html("<br/>"+err+"<br/>");
});
});
});
</script>
PHP/ajax_contact.php
<?php
function check_email_address($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
$naam = trim($_POST['naam']);
$bedrijf = trim($_POST['bedrijf']);
$tmail = trim($_POST['tmail']);
$tekst = trim($_POST['tekst']);
if(isset($naam ) && isset($tmail) && isset($tekst)){
if(!empty($naam) && !empty($tmail) && !empty($tekst)){
if(check_email_address($tmail)){
$to = 'name@something.com';
$subject = 'Some subject';
$message = 'Name: '.$naam.' //// Company: '.$bedrijf.'
-------------------------------------------------------
'.$tekst.'
-------------------------------------------------------
Sended on: '.date("F j, Y, g:i a").' - from: www.somthing.com';
$headers = 'From: '. $tmail . "\r\n" .
'Reply-To: '. $tmail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo '0'; //Succes <3
}else{
echo '1'; //Invalid mail adres
}
}else{
echo '2'; //Empty fields
}
}else{
echo '3'; //Fail post
}
?>