Skip to content Skip to sidebar Skip to footer

Set Jquery Button Instead Of Php Error And Success Status

Here is my index.html:

Get Email Update

Solution 1:

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

        returnfalse; 
    }); 
});

Post a Comment for "Set Jquery Button Instead Of Php Error And Success Status"