douduanque5850 2015-03-03 11:10
浏览 37
已采纳

设置jquery按钮而不是php错误和成功状态

Here is my index.html:

<body>

        <div id="newsletterform">
            <div class="wrap">
                <h3>Get Email Update</h3>
                <form action="send.php" method="post" id="newsletter" name="newsletter">
                    <input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
                    <button class="btn btn-7 btn-7h icon-envelope">Submit form</button>

                    <span class="arrow"></span>
                </form>
                <div id="response"></div>
            </div>
        </div>

 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="assets/js/lib.js"></script>
      </body>

And here is my send.php:

<?php

$host   = "";
$dbname = "";
$user   = "";
$pass   = "";

$email    = filter_var($_POST['signup-email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');

try {
    $db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

    if (empty($email)) {
        $status = "error";
        $message = "The email address field must not be blank";
    } else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
        $status = "error";
        $message = "You must fill the field with a valid email address";
    } else {
        $existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
        $existingSignup->execute();
        $data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;

        if (!$data_exists) {
            $sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
            $q = $db->prepare($sql);
            $q->execute(
                array(
                    ':email' => $email,
                    ':datetime' => $datetime
            ));

            if ($q) {
                $status = "success";
                $message = "You have been successfully subscribed";
            } else {
                $status = "<button class="btn btn-7 btn-7h icon-envelope">Submit form</button>";
                $message = "An error occurred, please try again";
            }
        } else {
            $status = "<button class="btn btn-7 btn-7h icon-envelope">Submit form</button>";
            $message = "This email is already subscribed";
        }
    }

    $data = array(
        'status' => $status,
        'message' => $message
    );

    echo json_encode($data);

    $db = null;
}
    catch(PDOException $e) {
    echo $e->getMessage();
}
?>

I have been created subscribe form using html, php and sql.

It works fine, Now i need to update like, use error and success button instead of displayed error or success message.

so that i created two buttons that is error and success, Now i need to add in my index page. If i enter wrong email id or blank or repeated mail id means, it shows error button or else success button.

Button should be like this: I have been created in jsfiddle: http://jsfiddle.net/b9y5bunp/3/

May i know, how to achieve this one, Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dounan4479 2015-03-03 12:35
    关注

    In PHP set $status with the results whether it is 'error' or 'success'

        if (!$data_exists) {
            $sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
            $q = $db->prepare($sql);
            $q->execute(
                array(
                    ':email' => $email,
                    ':datetime' => $datetime
            ));
    
            if ($q) {
                $status = "success";
                $message = "You have been successfully subscribed";
            } else {
                $status = "error";
                $message = "An error occurred, please try again";
            }
        } else {
            $status = "error";
            $message = "This email is already subscribed";
        }
    

    In HTML, add a id to the button like id="actbtn"

    <button id="actbtn" class="btn btn-7 btn-7h icon-envelope">Submit form</button>
    

    In Javascript, updated the ajax request to following

    $(document).ready(function () { 
        $('#newsletter').submit(function () { 
            var $this = $(this), 
            $response = $('#response'), 
            $mail = $('#signup-email'), 
            testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/, 
            hasError = false; 
    
            $response.find('p').remove(); 
    
            if (!testmail.test($mail.val())) {
                $('#actbtn').removeClass('btn-error').addClass('btn-error');
                //$response.html('<p class="error">Please enter a valid email</p>'); 
                hasError = true; 
            } 
    
            if (hasError === false) { 
                $response.find('p').remove(); 
                $response.addClass('loading'); 
    
                $.ajax({ 
                    type: "POST", 
                    dataType: 'json', 
                    cache: false, 
                    url: $this.attr('action'), 
                    data: $this.serialize(),
                    success: function(data){
                        if(data!=''){
                            $response.removeClass('loading'); 
                            if(data.status == 'success'){
                                $('#actbtn').removeClass('btn-error').addClass('btn-success');
                            }
                            else{
                                $('#actbtn').removeClass('btn-error').addClass('btn-error');
                            }
                        }
                    }           
                });
            } 
    
            return false; 
        }); 
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog