Snehal
Snehal

Reputation: 137

Don't allow ajax url to submit if validation false

I have 2 text boxes in a form.I don't want to allow ajax url to submit if any of the validation is false.How can i achieve this.I dont know much about jquery. Please help.

<div class="coupon" style="display:none;">                              
    <input type="text" class="coupon-name" name="fullname"  id="fullname">
    <span class="name-error"></span>
    <input type="text" class="coupon-email" name="email" id="email">
    <span class="email-error"></span>
    <button type="submit" value="status_add" name="status_add" id="add-status"    onclick="checkStatus()">Apply</button>
</div>  

<script type="text/javascript">
function checkStatus(){
        var fullname = $(".coupon-name").val();
        var email = $(".coupon-email").val();

        if(fullname == ''){
            $('input[name="fullname"]').next('span').text('Please Enter Your Name');
        }
        if(email == ''){
            $('input[name="email"]').next('span').text('Please Enter a Email Id');
        }                               

        $.ajax(
        {
            url     : "<?php echo base_url('myaccount/validate/'); ?>",
            type    : "POST",
            data    : {fullname: fullname,email:email} ,

Upvotes: 0

Views: 242

Answers (4)

Snowno Wang
Snowno Wang

Reputation: 36

you can use this:<input type="button" /> and <form id="form" method="post" action="xxxxx.php">

if you js code ok then do this:$('#form').submit();

Upvotes: 0

viktarpunko
viktarpunko

Reputation: 353

You should use the boolean flag in the checkStatus.

function checkStatus(){
    var fullname = $(".coupon-name").val();
    var email = $(".coupon-email").val();

    var isValidate = true;

    if(fullname == ''){
        isValidate = false;
        $('input[name="fullname"]').next('span').text('Please Enter ..');
    }
    if(email == ''){
        isValidate = false;
        $('input[name="email"]').next('span').text('Please Enter a Email');
    }                               

    if (!isValidate) { return;}

    //ajax request
}

Upvotes: 2

Mr. J
Mr. J

Reputation: 320

Try this,

Use return false;

var fullname = $(".coupon-name").val();
        var email = $(".coupon-email").val();
        var error=0;
        if(fullname == ''){
            $('input[name="fullname"]').next('span').text('Please Enter Your Name');
         error=1;
        }
        if(email == ''){
            $('input[name="email"]').next('span').text('Please Enter a Email Id');
         error=1;
        } 

       if(error>0){
         return false;
        }

Upvotes: 2

Twinfriends
Twinfriends

Reputation: 1997

Did not spend much time on you're code, don't know if there are any other errors, but may you should put the ajax part in a "else" condition, otherwise it will be done everytime, independent of the result of the two if-conditions.

Upvotes: 2

Related Questions