没有使用ajax从php文件接收响应

Currently i am trying to send email using PHPMailer after submitting registration form but i am successfully receiving the email but not getting redirected or getting any message notice box after email has been sent.

The Signup form

        <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>

Here is the ajax work:

       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;
        }

Here is the PHP part which receives my form inputs and send code and email to the email php file

    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();
            }
}

The 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;
}

}

Now if i remove the send_code($code,$email) from the register.class.php then i am successfully receiving the redirection and notice.I have tried almost 3 hours but not getting to any point.

UPDATE1: i have enabled error_reporting and display_error but i am not receiving any errors in the phperror log and also no error in the console of chrome . I have tried using console.log(response) and i am receiving the email in my gmail properly and also i am receiving the response 'emailact' properly but why am i not getting redirected? the log is as follow :

2018-07-21 14:53:03 CLIENT -> SERVER: This is the HTML message body <b>in bold!</b>9759376
2018-07-21 14:53:03 CLIENT -> SERVER:
2018-07-21 14:53:03 CLIENT -> SERVER:
2018-07-21 14:53:03 CLIENT -> SERVER: --b1_vph8ZrSzb5duNdneV6Z64s04gZP7o2um2oEAjFQXso--
2018-07-21 14:53:03 CLIENT -> SERVER:
2018-07-21 14:53:03 CLIENT -> SERVER: .
2018-07-21 14:53:04 SERVER -> CLIENT: 250 2.0.0 OK 1532184784 v4-v6sm5199360wra.22 - gsmtp
2018-07-21 14:53:04 CLIENT -> SERVER: QUIT
2018-07-21 14:53:04 SERVER -> CLIENT: 221 2.0.0 closing connection v4-v6sm5199360wra.22 - gsmtp
emailact

UPDATE 2:(SOLVED) At last i solved it its not the issue with the email.class.php but i think its with the response in my final log console.log(response) i was receiving the complete work load of php mailer well i think the whole log along with the 'emailact' that i was echoing ,was the 'response'.By considering this i arranged js in success function as follows:

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);               
        }
}

</div>
dougou8552
dougou8552 我看到花括号在email.class.php中不平衡。如果是复制错误那么抱歉!
2 年多之前 回复
doucan1979
doucan1979 请检查我的问题更新。
2 年多之前 回复
duanqi5333
duanqi5333 感谢准备好的声明指南(这不是我的最终版本,我将在完成此项目之前尝试编写预备语句)。
2 年多之前 回复
douxie1692
douxie1692 您的脚本对SQL注入攻击是开放的即使您正在逃避输入,它也不安全!在MYSQLI_或PDOAPI中使用准备好的参数化语句
2 年多之前 回复
duanchi4544
duanchi4544 为什么在每次创建新帐户时,您希望ALTERTABLE用户AUTO_INCREMENT=1。这可能是通过尝试在您创建的每个新帐户上创建重复ID而导致mysql错误
2 年多之前 回复
dongxuying7583
dongxuying7583 如果您在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);到你的脚本的顶部。
2 年多之前 回复
dsxmwin86342
dsxmwin86342 你在哪里调用函数regform()?
2 年多之前 回复
doudaiyao0934
doudaiyao0934 你检查了你在ajax方面收到的回复吗?
2 年多之前 回复
dongshao1873
dongshao1873 仍然没有收到消息或重定向。似乎没有工作。
2 年多之前 回复
dongshou2017
dongshou2017 删除标题('location:../verification.php?verify='。$email);
2 年多之前 回复
douchun3680
douchun3680 window.location.href也有效,但我认为email.class.php存在一个问题,即为什么我没有收到回复,即使我收到了email.calss.php的邮件
2 年多之前 回复
dongmi4927
dongmi4927 而不是window.location.href尝试使用window.location来执行实际的重定向
2 年多之前 回复

1个回答

Your ajax is fine and it's sending data to the php file but, php cannot access the information because yo didn't define (I don't know what they call this) Let's say method name:

$.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>');
            },

The second thing is in your core/register.class.php you didn't define the parameters correctly, This is the right way to get the serialized data:

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();
            }
}

I think this will work fine for you.

dqrfdl5708
dqrfdl5708 但幸好我解决了这个问题,感谢ajax的正确方法。
2 年多之前 回复
dongmei8460
dongmei8460 谢谢你的答案,但PHP正在访问信息,因为我的用户已在我的数据库中注册,我也收到验证的电子邮件,如果我根据ajax成功功能更改我的设置不发送电子邮件我也得到重定向和消息 两个回复'adminact'和'noact'。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐