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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line