Respuesta AJAX de PHP para deshabilitar un botón.

He intentado buscar alrededor de las últimas 1 horas en Stack Overflow, probando diferentes métodos sin métodos de trabajo, así que pensé que era hora de hacer un hilo.

De acuerdo, déjame intentar explicar lo que estoy tratando de hacer;

1) El usuario ingresa el nombre de usuario en el campo 2) AJAX envía y verifica el nombre de usuario contra la base de datos 3) Si se toma el nombre de usuario, js desactiva el botón de envío 4) de lo contrario, si no lo está, js les permite enviarlo.

¡Te mostraré mi código actual! Este mi js?

 $(document).ready(function () { $("#username").blur(function () { var username = $(this).val(); if (username == '') { $("#availability").html(""); } else{ $.ajax({ url: "class.validation.php?username="+username }).done(function( data ) { $("#availability").html(data); if($.html(data) == 'success') { alert('blah') } }); } }); });  

Este es el 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 result if (in_array($username, $array) == 1) { echo ""; exit(); }elseif (strlen($username) < 3){ echo 'not enough char'; echo ""; exit(); }elseif (mysqli_num_rows($resultSet) == 0) { echo ""; die(); } else{ echo "That username has been taken!"; echo ""; die(); } 

Y el HTML que estoy usando para mostrar el mensaje;

    

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 result if (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'] = 'http://sofes.miximages.com/javascript/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

    

En su .done() callback:

 .done(function( data ) { // Prints the response of your php script $('#availability').html(data); // Checks wether to disable the button or not if(data == 'That username has been taken!' || data == 'not enough char') { $("#submit").attr('disabled', 'disabled'); } else { $("#submit").removeAttr("disabled"); } }); 

Si bien hay una respuesta que te ayuda con el problema, sugeriré usar JSON para definir los mensajes de error de PHP. De esa manera, no está creando tags de cadena html en su PHP, haciéndolo lo más limpio posible ya que se trata de datos (¡exactamente lo que debería estar haciendo!).

Tu JS podría ser:

 $(document).ready(function () { $("#username").blur(function () { // Adding your field as variable to ease any ID changes var username = $(this).val(), divAvailable = $("#availability"); // Client-side validation if (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 = $("

"), imageElement = $(""); // 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

tag html messageElement.html(data.message); // Setting 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); } }); } }); });

Su 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'] = "http://sofes.miximages.com/javascript/cross.png"; } elseif (strlen($username) < 3){ $validation['message'] = "not enough char"; $validation['image'] = "http://sofes.miximages.com/javascript/cross.png"; } elseif (mysqli_num_rows($resultSet) == 0) { $validation['valid'] = true; $validation['image'] = "http://sofes.miximages.com/javascript/accept.png"; } else { $validation['message'] = "That username has been taken!"; $validation['image'] = "http://sofes.miximages.com/javascript/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); 

Incluso agregaría algunas constantes en PHP para contener las URL y los mensajes de la imagen también. De esa manera, solo podría llamar a la constante, sin necesidad de buscar todo el código donde se encuentran las imágenes URL.

¡Recuerda, no te repitas!