【问题标题】:Not receiving response from php file using ajax使用ajax没有收到来自php文件的响应
【发布时间】:2018-07-21 23:17:34
【问题描述】:

目前我正在尝试在提交注册表后使用 PHPMailer 发送电子邮件,但我成功收到了电子邮件,但在发送电子邮件后没有被重定向或收到任何消息通知框。

注册表单

        <form id="form_register" method="post" class="form-horizontal">
		<span id="log"></span>
            <div class="form-group mb5">
                <label for="username" class="col-xs-12 mb0">Username</label>
                <div class="col-xs-12">
					<input type="text" class="form-control" placeholder="Username" name="username" id="username">
				</div>
            </div>
            <div class="form-group mb5">
                <label for="login-password" class="col-xs-12 mb0">First Name</label>
                <div class="col-xs-12">
                    <input type="text" class="form-control" placeholder="First Name" name="first_name" id="first_name">
                </div>
            </div>
            <div class="form-group mb5">
                <label for="login-password" class="col-xs-12 mb0">Last Name</label>
                <div class="col-xs-12">
                    <input type="text" class="form-control" placeholder="Last Name" name="last_name" id="last_name">
                </div>
            </div>
            <div class="form-group mb5">
                <label for="login-password" class="col-xs-12 mb0">Email</label>
                <div class="col-xs-12">
                    <input type="email" class="form-control" placeholder="Email address" name="email" id="email">
                </div>
            </div>
            <div class="form-group mb5">
                <label for="login-password" class="col-xs-12 mb0">Password</label>
                <div class="col-xs-12">
                    <input type="password" class="form-control" placeholder="Password" name="password" id="password">
                </div>
            </div>
            <div class="form-group mb5">
                <label for="login-password" class="col-xs-12 mb0">Confirm Password</label>
                <div class="col-xs-12">
                    <input type="password" class="form-control" placeholder="Confirm Password" name="confirm_pass" id="confirm_pass">
                </div>
            </div>
			<div class="form-group">
                <label class="col-md-3 control-label text-left" for="gender">Gender</label>
                <div class="col-md-9">
                    <select id="gender" name="gender" class="form-control" size="1">
                        <option value="male">Male</option>
                        <option value="female">Female</option>
						<option value="other">Other</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="col-xs-7">
                </div>
                <div class="col-xs-5 text-right">
                    <button type="submit" class="btn btn-effect-ripple btn-sm btn-warning btn-block" name="create_account" id="create_account"><i class="fa fa-user-plus"></i> Sign up</button>
                </div>
            </div>
        </form>

这里是 ajax 工作:

	   function regform()
	   {		
			var data = $("#form_register").serialize();
			$.ajax({
			type : 'POST',
			url  : 'core/register.class.php',
			data : data,
			beforeSend: function()
			{	
				$("#log").fadeOut();
				$("#create_account").html('<i class="fa fa-spinner fa-spin"></i>');
			},						
			success : function(response){
					if(response=="emptycaptcha"){
						$("#log").fadeIn();
						$("#log").html('<div class="notice notice-sm notice-danger"><strong><i class="fa fa-info-circle"></i> Empty Captcha</strong> Please fill in the captcha to continue.</div>');
						$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');			
					}else if(response=="wrongcaptcha"){ 
						$("#log").html('<div class="notice notice-sm notice-danger"><strong><i class="fa fa-info-circle"></i> Wrong Captcha</strong> Please fill in the captcha correctly.</div>');
						$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
					}else if((response=="noact") || (response=="adminact")){
						$("#log").fadeIn();
						$("#log").html('<div class="notice notice-sm notice-success"><strong><i class="fa fa-info-circle"></i> Successfully Registered!</strong> You will be redirected to Login Page...</div>');
						$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
						setTimeout(function() {
							window.location.href = "login.php";
						}, 5000);					
					}else if(response=="emailact"){
						$("#log").fadeIn();
						$("#log").html('<div class="notice notice-sm notice-success"><strong><i class="fa fa-info-circle"></i> Successfully Registered!</strong> A Verification Email has been sent to your email.You will be redirected to verification page...</div>');
						$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
						var uemail = $('#email').val();
						setTimeout(function() {
							window.location.href = "verification.php?verify="+uemail;
						}, 5000);				
					}		
			},				
			 error: function(response){
				 $("#log").html('<div class="notice notice-sm notice-danger"><strong><i class="fa fa-info-circle"></i> Error !</strong> Something went wrong.</div>');
			 }
			});
				return false;
		}

这是接收我的表单输入并将代码和电子邮件发送到电子邮件 php 文件的 PHP 部分

    if (isset($_POST['create_account'])){   
            $username = trim($_POST['username']);
             $first_name = trim($_POST['first_name']);
             $last_name = trim($_POST['last_name']);
             $email = trim($_POST['email']);
             $pass = trim($_POST['password']);
             $password = PASSWORD_HASH($pass, PASSWORD_BCRYPT);
             $gender = $_POST['gender'];
             $code = mt_rand(1111111, 9999999); 
             $reg_date = date('Y-m-d');
            try{
                $rai = $db_con->prepare("ALTER TABLE users AUTO_INCREMENT = 1");
                $rai->execute();                        
                if($settings['account_act']=='noact'){
                    $v_status = 'true';
                    $a_status = 'true';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    echo 'noact';
                }else if($settings['account_act']=='emailact'){
                    $v_status = 'false';
                    $a_status = 'false';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    send_code($code,$email);
                    echo 'emailact';    
                    }
                }else if($settings['account_act']=='adminact'){
                    $v_status = 'false';
                    $a_status = 'false';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    echo 'adminact';
                }
            }
            catch(PDOException $e){
                echo "sorry".$e->getMessage();
            }
}

email.class.php

function send_code($code,$email){
//Load composer's autoloader
require 'PHPMailer/vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'xxxxx';                 // SMTP username
    $mail->Password = 'xxxxx';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('xxxxxxxxx', 'xxxx');
    $mail->addAddress($email, 'User');     // Add a recipient
    //$mail->addAddress('ellen@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    //Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>'.$code;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    $mail->send();  
    //echo 'Message has been sent';
    header('location:../verification.php?verify='.$email);
    //echo 'emailact';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

}

现在,如果我从 register.class.php 中删除 send_code($code,$email),那么我将成功接收重定向和通知。我已经尝试了将近 3 个小时,但没有达到任何目的。

更新1: 我已启用 error_reporting 和 display_error 但我在 phperror 日志中没有收到任何错误,在 chrome 控制台中也没有收到错误。 我已经尝试使用 console.log(response) 并且我在我的 gmail 中正确接收到电子邮件,并且我也正确接收到响应“emailact”但为什么我没有被重定向?日志如下:

2018-07-21 14:53:03 CLIENT -> SERVER:这是 HTML 邮件正文粗体!9759376
2018-07-21 14:53:03 客户端 -> 服务器:
2018-07-21 14:53:03 客户端 -> 服务器:
2018-07-21 14:53:03 客户端 -> 服务器:--b1_vph8ZrSzb5duNdneV6Z64s04gZP7o2um2oEAjFQXso--
2018-07-21 14:53:03 客户端 -> 服务器:
2018-07-21 14:53:03 客户端 -> 服务器:.
2018-07-21 14:53:04 服务器 -> 客户端:250 2.0.0 OK 1532184784 v4-v6sm5199360wra.22 - gsmtp
2018-07-21 14:53:04 客户端 -> 服务器:退出
2018-07-21 14:53:04 服务器 -> 客户端:221 2.0.0 关闭连接 v4-v6sm5199360wra.22 - gsmtp
电子邮件操作

更新 2:(已解决) 最后我解决了它不是 email.class.php 的问题,但我认为它与我最终日志 console.log(response) 中的响应有关,我收到了 php mailer 的完整工作负载,我认为整个日志与我呼应的“电子邮件”是“响应”。考虑到这一点,我将 js 安排在成功功能中,如下所示:

success : function(response){
	console.log(response);
		if(response=="emptycaptcha"){
			$("#log").fadeIn();
			$("#log").html('<div class="notice notice-sm notice-danger"><strong><i class="fa fa-info-circle"></i> Empty Captcha</strong> Please fill in the captcha to continue.</div>');
			$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');			
		}else if(response=="wrongcaptcha"){ 
			$("#log").html('<div class="notice notice-sm notice-danger"><strong><i class="fa fa-info-circle"></i> Wrong Captcha</strong> Please fill in the captcha correctly.</div>');
			$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
		}else if((response=="noact") || (response=="adminact")){
			$("#log").fadeIn();
			$("#log").html('<div class="notice notice-sm notice-success"><strong><i class="fa fa-info-circle"></i> Successfully Registered!</strong> You will be redirected to Login Page...</div>');
			$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
			setTimeout(function() {
				window.location.href = "login.php";
			}, 5000);					
		}else{
		//if(response == "emailact"){
			$("#log").fadeIn();
			$("#log").html('<div class="notice notice-sm notice-success"><strong><i class="fa fa-info-circle"></i> Successfully Registered!</strong> A Verification Email has been sent to your email.You will be redirected to verification page...</div>');
			$("#create_account").html('<i class="fa fa-user-plus"></i> Sign Up');
			var uemail = $('#email').val();
			setTimeout(function() {
				window.location.href= "verification.php?verify="+uemail;
			}, 5000);				
		}
}

【问题讨论】:

  • 代替window.location.href 尝试window.location 执行实际重定向
  • window.location.href 也可以工作,但我认为 email.class.php 存在问题,即为什么即使我通过电子邮件收到邮件,我也没有收到回复。类.php
  • 删除标题('location:../verification.php?verify='.$email);
  • 仍然没有收到消息或重定向。似乎不起作用。
  • 请帮自己一个忙并启用完整的错误报告,如果您在 ajax 调用期间在 Web 浏览器网络选项卡中收到 500 错误,请查看您的服务器日志。或者,如果您没有收到 500,请查看原始响应数据。您说如果您不调用 send_code...,您会收到响应,这意味着您的问题完全在于 send_code 的函数定义。将此ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 添加到脚本的顶部。

标签: javascript php jquery html ajax


【解决方案1】:

您的ajax 很好,它正在将数据发送到php 文件,但是php 无法访问信息,因为您没有定义(我不知道他们称之为什么)让我们说方法名称:

$.ajax({
            type : 'POST',
            url  : 'core/register.class.php',
            data : {'create_account': data}, //********this is too important!!!
            beforeSend: function()
            {   
                $("#log").fadeOut();
                $("#create_account").html('<i class="fa fa-spinner fa-spin"></i>');
            },

第二件事是在您的core/register.class.php 中您没有正确定义参数,这是获取序列化数据的正确方法:

if (isset($_POST['create_account'])){   
            $get = explode('&', $_POST['create_account'] ); // explode with &

            foreach ( $get as $key => $value) {
                $valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] =  substr( $value,                strpos( $value, '=' ) + 1 ) ;
            }

        // access your query param
        $username = trim($valn['username']);
        $first_name = trim($valn['first_name']);
        $last_name = trim($valn['last_name']);
        $email = trim($valn['email']);
        $pass = trim($valn['password']);
        $password = PASSWORD_HASH($pass, PASSWORD_BCRYPT);
        $gender = $valn['gender'];
        $code = mt_rand(1111111, 9999999); 
        $reg_date = date('Y-m-d');
            try{
                $rai = $db_con->prepare("ALTER TABLE users AUTO_INCREMENT = 1");
                $rai->execute();                        
                if($settings['account_act']=='noact'){
                    $v_status = 'true';
                    $a_status = 'true';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    echo 'noact';
                }else if($settings['account_act']=='emailact'){
                    $v_status = 'false';
                    $a_status = 'false';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    send_code($code,$email);
                    echo 'emailact';    
                    }
                }else if($settings['account_act']=='adminact'){
                    $v_status = 'false';
                    $a_status = 'false';
                    $stmt = $db_con->prepare("INSERT INTO users(username,first_name, last_name, email, password, gender, a_status, reg_date, v_code, v_status) VALUES(:uname, :fn, :ln, :email, :pass, :gender, :a_status, :regd, :code, :v_status)");
                    $stmt->execute(array(":uname"=>$username,":fn"=>$first_name,":ln"=>$last_name,":email"=>$email,":pass"=>$password,":gender"=>$gender,":a_status"=>$a_status,"regd"=>$reg_date,":code"=>$code,":v_status"=>$v_status));
                    echo 'adminact';
                }
            }
            catch(PDOException $e){
                echo "sorry".$e->getMessage();
            }
}

我认为这对你来说很好。

【讨论】:

  • 感谢您的回答,但 php 正在访问信息,因为我的用户正在我的数据库中注册,而且我还收到了验证电子邮件,如果我将我的设置更改为不根据 ajax 成功发送电子邮件功能我也得到了重定向和消息与两个响应'adminact'和'noact'。
  • 但幸运的是我解决了这个问题,感谢正确的 ajax 方法。
猜你喜欢
  • 2021-10-29
  • 2017-05-20
  • 1970-01-01
  • 2013-03-14
  • 2020-08-04
  • 1970-01-01
  • 2015-03-05
  • 2013-01-05
  • 2014-09-17
相关资源
最近更新 更多