驗證我有這個腳本PHPMailer的git的問題:https://github.com/Krishneil1/Contact-Form-PHPPHPMailer的使用AJAX
這個腳本作品,未經我的一個問題,但我想添加AJAX和發送郵件時,驗證是正確的。通常當驗證不正確時,頁面被重新加載,但是當重新加載不正確時我不想重新加載網頁,但是在同一頁面上顯示錯誤。我希望你明白我的意思。我怎麼能這樣做?
我contact.php文件:
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors =[];
if(isset($_POST['name'],$_POST['email'],$_POST['message'])){
$fields=[
'name'=>$_POST['name'],
'email'=>$_POST['email'],
'message'=>$_POST['message']
];
foreach($fields as $field=>$data){
if(empty($data)){
$errors[]='The '.$field . ' field is required.';
}
}
if(empty($errors)){
$m=new PHPMailer;
$m->isSMTP();
$m->SMTPAuth=true;
$m->Host='smtp.gmail.com';
$m->Username='[email protected]';//replace by your email address
$m->Password='password';//replace with your password
$m->SMTPSecure='ssl';
$m->Port=465;
$m->isHTML();
$m->Subject ='Contact form Submitted';
$m->Body='From:'.$fields['name'].'('.$fields['email'].')<p>'.$fields['message'].'</p>';
$m->FromName='Contact';
$m->AddAddress('[email protected]','Some one');
if ($m->send()) {
header('Location:thanks.php');
die();
}else{
$errors[]="Sorry ,Could not send email.Try again later.";
}
}
}else{
$errors[]= 'Something went wrong';
}
$_SESSION['errors']=$errors;
$_SESSION['fields']=$fields;
header ('Location:index.php');
而且index.php文件是git的鏈接主網站上。
我的AJAX文件:
$(function() {
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
const url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
dataType: 'json',
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
return false;
}
})
});
也請更新你至今嘗試過的代碼的問題。 – codePG
@codePG更新。 – kristoff090