I'm busy on a register form, but the biggest part is jQuery. So I wanna validate the inputs using jQuery too. After lots of thinking, this is what I came up with;
$('#usernameDone').click(function()
{
$.post('public/robin/check_existing.php',{value: $("#username").val()}, function(data){
window.alert(data);
if(data == true){
window.alert("Name exists");
}else{
window.alert("Name doesnt exist");
}
});
(I know the 'click' function isn't closed, but that's because there's some stuff after it.)
So it posts the value of the #username
input field into check_existing.php
, which looks like this;
<?php
$value = $_POST['value'];
$db = new MySQLi('127.0.0.1', 'root', '*******', 'htv1.1');
$query = $db->prepare('SELECT * FROM ht_users WHERE naam = ?');
$query->bind_param('s', $value);
$query->execute();
if ($query->num_rows > 0)
{
return true;
}
else
{
return false;
}
Please note this is not the method I normally use. This was more like a 'testbench'.
The only thing is; it always returns one empty alert box, and then it shows 'name doesnt exist'.
How can I solve this problem?
In your case, the return
statement in PHP is just stopping execution. You need to send the data to the actual response, eg using echo
:
if ($query->num_rows > 0)
{
echo "true";
}
else
{
echo "false";
}
The first javascript alert
is blank as no data is being returned from PHP, which evaluates as false
.
Change the PHP to read
if ($query->num_rows > 0)
{
echo "true";
}
else
{
echo "false";
}
Then the JS to read
if(data == "true"){
I think you are using $.POST wrong. 'data' can never have any value in your code. It is and will be undefined.
Look at the code from the documentation: http://api.jquery.com/jquery.post/
Here is a snipped that should work:
$.post( "ajax/test.html", function( data ) {
alert(data);
// Go ahead with your code.
});
So use an anonymous function that takes (data) and proceed from there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.