Tonza Tonza - 5 months ago 19
jQuery Question

Return to previous function

I'm using ajax to check if username is taken.

If username is taken it return false to form submit function.

I'm using mysql.

index.php

$("#register-form").submit(function(){
var un = $("#un").val();
$.ajax({
type: "GET",
url: "user_check.php",
dataType: "html",
data: {un: un},
success: function(data){

}
});
});


user_check.php

$db = mysqli_connect("localhost","root","","webcap");
$user = $_POST['un'];
$query = mysqli_query($db,"SELECT * FROM users WHERE username='$un'");
$count = mysqli_num_rows($query);
echo $count;


How i return false to register form submit function if data is 1 or true if its 0?

Is there easier way to do this?

Answer

Use JSON. In the PHP do:

echo json_encode($count > 0);

And in the Javascript, specify type: 'json' instead of type: 'html'. Then data will be true or false.

However, since AJAX is asynchronous, you can't return a value from this.

What you need to do is prevent normal form submission in the .submit() function. Then in the success: function, check the response and submit the form if it was successful.

$("#register-form").submit(function(e){
    e.preventDefault();
    var un = $("#un").val();
    $.ajax({
        type: "GET",
        url: "user_check.php",
        dataType: "json",
        data: {un: un},
        success: function(data){
            if (data) {
                $("#register-form")[0].submit(); // really submit the form
            } else {
                alert("Username is taken");
            }
        }
    });
});
Comments