1

I have input field where user can enter username. When user submit username it is inserted in mySQL database. If username is already in database ajax checks it and returns x and if it is not in database it return check icon. Problem is that I need to disable submit button when ajax returns x.

This is my code:

<div id="loginform">
                <form id="login" name="login" method="POST" action="process.php">
                    <div class="col-lg-6">
                        <span>Username:</span><br>
                       <input type="text" id="username" name="username" placeholder="Username" class="required"/>
                        <span id="user-result"></span>

                    </div>
                    <div class="col-lg-6">
                        <span>Password</span><br>        
                        <input type="password" id="password" name="password" placeholder="password" class="required" />
                    </div>
                    <div class="col-lg-12">
                        <span>E-mail:</span><br>
                        <input type="text" id="email" name="email" placeholder="Email" class="required email" />
                        <span id="mail-result"></span>
                    </div>

                    <div class="col-lg-6">     
                        <input id="submit" name="submit" type="submit" value="Send It" />

                    </div>
                </form>
                <div id="response"></div>
                <div id="loading"><img src="../images/preloader.png" alt=""/></div>
            </div>

js:

 $(document).ready( function() {
$('input[placeholder], textarea[placeholder]').placeholder();
$('#submit').removeAttr('disabled');



$('#login').validate({
    debug: true,
    //submitHandler: ajaxSubmit
            rules: {
                username: {
                    required: true,
                    minlength: 3,
                    maxlength: 255
                },
                password: {
                    required: true,
                                            minlength: 8,
                                            maxlength: 255
                }
            },
            messages: {
                username: "Username field required.",
                password: "Password field required.",
                email: {
                    required: "Email address required",
                    email: "Email address must be in the format name@domain.com."                        
                }


            }

});


$('#submit').click( function() {
    if( $('#login').valid() ) {
            ajaxSubmit();
    }
    else {
        $('label.error').hide().fadeIn('slow');

    }
});




    var username  = $.trim($('#username').val());


$("#username").keyup(function (e) {

    //removes spaces from username
    $(this).val($(this).val().replace(/\s/g, ''));

    var username = $(this).val();
    if(username.length < 4){
                $("#user-result").html('');

                return;
            }

    if(username.length >= 4){
        $("#user-result").html('<img src="images/ajax-loader.gif" />');
        $.post('../check_username.php', {'username':username}, function(data) {
          $("#user-result").html(data);

        });
    }

});;


    $("#email").keyup(function (e) {

    //removes spaces from email
    $(this).val($(this).val().replace(/\s/g, ''));

    var email = $(this).val();
    if(email.length < 4){
                $("#mail-result").html('');

                return;
            }

    if(email.length >= 4){
        $("#mail-result").html('<img src="images/ajax-loader.gif" />');
        $.post('../check_username.php', {'email':email}, function(data) {
          $("#mail-result").html(data);

        });
    }
});;


$(document).ajaxStart(function() {
$("#submit").prop('disabled', true);
}).ajaxStop(function() {
$("#submit").prop('disabled', false);
});













});




function ajaxSubmit() {
$('#loading').show();
$('#submit').attr('disabled', 'disabled');
var username = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();

var data = 'username=' +username+ '&password=' +password+ '&email=' +email;

$.ajax({
    url: '../process.php',
    type: 'get',
    dataType: 'json',
    data: data,
    cache: false,
    success: function(response) {
        if( response.error != 'true' ) {
            $('#loading, #login, .message').fadeOut('slow');
            $('#response').html('<h3>Records added successfully.</h3>').fadeIn('slow');
        }
        else {
                $('#loading').fadeOut('slow');
                $('#submit').attr('disabled', 'disabled');
                $('#response').html('<h3>Could not able to execute sql</h3>').fadeIn('slow');
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
                            $('#loading').fadeOut('slow');
            $('#submit').removeAttr('disabled');
            $('#response').text('Error Thrown: ' +errorThrown+ '<br>jqXHR: ' +jqXHR+ '<br>textStatus: ' +textStatus ).show();
    }
});
return false;
}

php:

<?php

// Connect to database
include 'includes/database.php';

 //check we have username post var
if(isset($_POST["username"]))
{
//try connect to db
include 'includes/database.php';


//sanitize username
    $username = mysqli_real_escape_string($link, $_POST['username']);

//check username in db
$results = mysqli_query($link,"SELECT * FROM users WHERE username='$username'");

//return total count
$username_exist = mysqli_num_rows($results); //total records

//if value is more than 0, username is not available
if($username_exist) {


    die('<img src="images/not-available.png" />');

}else{
    die('<img src="images/available.png" />');

}
    }
    if(isset($_POST["email"]))
    {
    //sanitize mail
    $email = mysqli_real_escape_string($link, $_POST['email']);

//check mail in db
$results_mail = mysqli_query($link,"SELECT * FROM users WHERE email='$email'");

//return total count
$email_exist = mysqli_num_rows($results_mail); //total records

//if value is more than 0, mail is not available
if($email_exist) {
    die('<img src="images/not-available.png" />');

}else{
    die('<img src="images/available.png" />');

}

//close db connection
mysqli_close($link);
    }

EDIT:

    if(username.length >= 4){
        $("#user-result").html('<img src="images/ajax-loader.gif" />');
        $.post('../check_username.php', {'username':username}, function(data) {
                        console.log(data);
                        if (data == 'No' ){
                           $("#submit").prop('disabled', true);
          $('#user-result').html('<img src="images/not-available.png" />')

                    }else{
                        $("#submit").prop('disabled', false);
          $('#user-result').html('<img src="images/available.png" />')
                    }

        });
    }

I get images if username is taken but can't get button disabled

and here is my PHP

//check we have username post var
if(isset($_POST["username"]))
{
//try connect to db
include 'includes/database.php';


//sanitize username
    $username = mysqli_real_escape_string($link, $_POST['username']);

//check username in db
$results = mysqli_query($link,"SELECT * FROM users WHERE username='$username'");

//return total count
$username_exist = mysqli_num_rows($results); //total records

//if value is more than 0, username is not available
if($username_exist) {

echo'No';
    //die('<img src="images/not-available.png" />');

}else{
    //die('<img src="images/available.png" />');
            echo'Yes';
}
    }
KondukterCRO
  • 543
  • 2
  • 16
  • 31
  • I have prefer to use jquery remote method rather then this complex approach.Refer [this](http://jqueryvalidation.org/remote-method/) link may help you. – Nikunj Chotaliya Aug 04 '15 at 06:57
  • [This](http://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) will answer your question. –  Aug 04 '15 at 07:02
  • Thank you for answers, but everything works now and I am trying to disable submit in if statement. I edited code so does anyone see where I made mistake? – KondukterCRO Aug 04 '15 at 09:01

2 Answers2

1

I added this to my js:

if(username.length >= 1){
        $("#user-result").html('<img src="images/ajax-loader.gif" />');
        $.post('../check_username.php', {'username':username}, function(data) {
                       // console.log(data);
                        if (data == 'No' ){
                          $("#submit").prop('disabled', true);
          $('#user-result').html('<img src="images/not-available.png" />')

                    }else{
                       $("#submit").prop('disabled', false);
          $('#user-result').html('<img src="images/available.png" />')
                    }

        });
    }

and this to php:

  if($username_exist) {

echo'No';


}else{

            echo'Yes';
}

and that solved problem

thanks everybody for help

KondukterCRO
  • 543
  • 2
  • 16
  • 31
0

I created this JSFiddle example to disable a button with Jquery:

$('#submit').prop('disabled', true);

Disable a button example

Tariq
  • 2,853
  • 3
  • 22
  • 29
  • Maybe you misunderstood my question but I know how to disable submit but I have problem making it work in my if statement. You can check my edited question and where I call ajax to check if username is taken and if it is true disable submit. But it don't work. But yes, your example works great ;) – KondukterCRO Aug 04 '15 at 09:17
  • Did you check the server response? what echo $username_exist gives on server? Did you try using if($username_exist > 0)? – Tariq Aug 04 '15 at 09:45