来自PHP的AJAX响应禁用按钮

我已经尝试在Stack Overflow上搜索过去1小时,尝试使用不同的方法而没有工作方法,所以认为它的时间是一个线程。

好的,让我试着解释一下我要做的事情;

1)用户输入用户名到字段2)AJAX发送并检查用户名对数据库3)如果用户名,js禁用提交按钮4)否则,如果不是,js允许他们提交。

我会告诉你我目前的代码! 这是我的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') } }); } }); });  

这是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(); } 

我用来显示消息的HTML;

    

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://sofzh.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

    

.done()回调中:

 .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"); } }); 

虽然有一个答案可以帮助您解决问题,但我建议使用JSON来定义PHP的错误消息。 这样,您就不会在PHP上创建html字符串标记,因为它处理数据(确切地说它应该做什么!),因此尽可能地保持最清晰。

你的JS可能是:

 $(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); } }); } }); });

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

我甚至会在PHP上添加一些常量来保存图像url和消息。 这样你只能调用常量,而不需要搜索你的图像url所在的所有代码。

记住,不要重复自己!