ajax - check if a username exists + return message if it does

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.

I'm having some trouble and have a few questions.

I have my input field plus js:

<script src="js/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){  $('#username').on('blur', checkdb);  function checkdb(){      var desiredUsername = $(this).val();     $.ajaxSetup({         url: "check-db.php",         type: "POST",     });      $.ajax({         data: 'desiredUsername='+desiredUsername,                success: function (msg) {             alert (msg);},             error: function (XMLHttpRequest, textStatus, errorThrown){                alert('Error submitting request.');          }        });      }            }); </script>  <input type="text" name="username" id="username"> 

and my check-db.php file:

$mysqli = mysqli_connect("localhost","connection info"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; }  $desiredUsername = $_POST['desiredUsername'];   $stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' "); $stmt->bind_param('s', $desiredUsername); $stmt->execute(); 

firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?

then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?

thanks!

回答1:

On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :

echo json_encode($datas); //can be array or whatever 

Then on the Client side :

$.ajax({     method: 'POST',     dataType:'json',     data: {'username' : desiredUsername}, //then getting $_POST['username']     success: function(datas) {         console.log(datas); //Your previous data from the server side     },     error: function(XMLHttpRequest, textStatus, errorThrown){             console.log(textStatus);     } }); 


回答2:

try

function checkdb(){      var desiredUsername = $(this).val();     $.ajaxSetup({         url: "check-db.php",         type: "POST",     });      $.ajax({         data: {             desiredUsername: desiredUsername         },         success: function (msg) {             alert(msg);         },         error: function (XMLHttpRequest, textStatus, errorThrown){                 alert('Error submitting request.');          }        });     }  


回答3:

You have an error when sending the data, you should send a JS Object as data, like this:

data: { desiredUsername: desiredUsername }, 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!