Skip to content Skip to sidebar Skip to footer

Ajax Response From Php To Disable A Button

I've tried searching around for past 1 hour on Stack Overflow, trying different methods with no working methods, so thought its time ti make a thread. Okay so let me try explain wh

Solution 1:

JavaScript

$('#username').blur(function() { // typical usage
$('#username').keyup(function() { // or use THIS to check after each keystroke!if ($(this).val() === '') {
        $('#loginButton').attr('disabled','disabled');
        $('#availability').attr('src','https://cdn2.iconfinder.com/data/icons/ledicons/cross.png');
        $('#loginMessage').text('Username may not be blank!');
    } else {
        $.getJSON('class.validation.php',{username:username},function(data) {
            $('#availability').attr('src',data.icon);
            $('#loginMessage').text(data.msg);
            if (data.isValid === true) {
                $('#loginButton').removeAttr('disabled');
            } else {
                $('#loginButton').attr('disabled','disabled');
            };
        });
    }
});

PHP

$username = $_GET['username'];
$username = strtolower($username);
$stmt = $mysqli->prepare("SELECT username FROM databasename WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$resultSet = $stmt->get_result();
$array = array('name1', 'name2', 'name3', 'name4');
//Prints the resultif (in_array($username, $array) == 1) {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'$sback['isValid'] = false;
    $sback['msg'] = 'That username is already in use!';
} elseif (strlen($username) < 3){
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'$sback['isValid'] = false;
    $sback['msg'] = 'That username is too short!';
} elseif (mysqli_num_rows($resultSet) == 0) {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/accept.png'$sback['isValid'] = true;
    $sback['msg'] = 'That username is available!';
} else {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'$sback['isValid'] = false;
    $sback['msg'] = 'There was a problem!';
}
echo json_encode($sback,JSON_PRETTY_PRINT);

HTML

<input type="text"id="email" name="email" class="email_landing" placeholder="Enter your email address">
<input type="text"id="username" name="username" class="username_landing" placeholder="Choose your username">
<input type="submit" class="submit_landing"id="loginButton" name="submit" value="Claim">
<div><img id="availability" /></div>
<div id="loginMessage"></div>

Solution 2:

In your .done() callback:

.done(function( data ) {
    // Prints the response of your php script
    $('#availability').html(data); 

    // Checks wether to disable the button or notif(data == 'That username has been taken!' || data == 'not enough char') {
        $("#submit").attr('disabled', 'disabled');
    } else {
        $("#submit").removeAttr("disabled");
    }
});  

Solution 3:

While there is an answer that helps you with the problem, I'm going to suggest to use JSON to define error messages from PHP. In that way, you're not creating html string tags on your PHP, making it cleanest as possible since it's dealing with data (exactly what it should be doing!).

Your JS could be:

$(document).ready(function () {

  $("#username").blur(function () {
    // Adding your field as variable to ease any ID changesvar username      = $(this).val(),
        divAvailable  = $("#availability");

    // Client-side validationif (username.length == 0) {
      divAvailable.html('');
    } else {
      divAvailable.html('');

      // data allows you to send your GET values// making URL string clean. It receives an// object where index are GET indexes to be// handled by PHP, and values are... values!// // Datatype will tell to $.ajax callback// functions that anything that retuns as a// response from the request, is a JSON, so// you don't need to $.parseJSON(response).
      $.ajax({
        url: "class.validation.php",
        data: {username : username},
        dataType: 'json'
      }).done(function(data) {
        // Creating default html elements.var messageElement = $("<p class='validation-message'></p>"),
            imageElement   = $("<img class='validation-image' src=''>");

          // As data is a JSON, and JSON returns exactly// two keys, informing image and a message, you// only need to put them as any other string value// using jQuery methods.// Setting <p> tag html
          messageElement.html(data.message);

          // Setting <img> tag src attribute
          imageElement.attr('src', data.image);

          // Since we already cleaned the $("#availability")// element, it's just append both element. You  may// change the order as you see fit.
          divAvailable.append(messageElement);
          divAvailable.append(imageElement);

          // I knew data.valid would be useful somewhere!// Since valid is a boolean value and there is a// jQuery method that allow us to handle HTML element// attributes by setting them true or false, you // just need to use the very same data.valid value.
          $('.submit_landing').attr('disabled', !data.valid);
        }
      });   
    } 
  });
});

Your PHP:

$username   = $_GET['username'];
$username   = strtolower($username);

// Adding a new array that will be encoded as JSON$validation = array('message' => '', 'image' => '', 'valid' => false);

// Database stuff well done with statement.$stmt = $mysqli->prepare("SELECT username FROM databasename WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$resultSet = $stmt->get_result();

$array = array('name1', 'name2', 'name3', 'name4');

//Prints the result// To use json_encode function, we must have an array.// In each case, you only need to change the values already// setted.if (in_array($username, $array) == 1) {
    $validation['message'] = "Error Message #1";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
} elseif (strlen($username) < 3){
    $validation['message'] = "not enough char";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
} elseif (mysqli_num_rows($resultSet) == 0) {
    $validation['valid']   = true;
    $validation['image']   = "https://cdn1.iconfinder.com/data/icons/ledicons/accept.png";
} else {
    $validation['message'] = "That username has been taken!";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
}

// I even added a 'valid' key, for, whatever reason you may// have to only validate the valid key.// Then echo! it's not return, it's echo json_encode.echo json_encode($validation);

I would even add some constants on PHP to hold the image urls and messages as well. In that way you could only call the constant, not needing to searching all the code where are your images urls.

Remember, Don't Repeat Yourself!

Post a Comment for "Ajax Response From Php To Disable A Button"