简体   繁体   中英

Callback function not invoked

Hello I have this jQuery:

    $("#registerButton").click(function(){
    var email = $("#registerForm input[type='email']").val();
    var username = $("#registerForm input[type='text']").val();
    var password = $("#registerForm input[type='password']").val();
    if((!$.trim(email)) || (!$.trim(username)) || (!$.trim(password)))
        return false;
    $("#login").modal('hide');
    $("#login").on('hidden.bs.modal', function(){
        $.ajax({
            type: 'post',
            url: '?a=register',
            data: {
                "email" : email,
                "username" : username,
                "password" : password
            },
            success: function(){
                $("#test").html("Testing callback function");
            }
        });
    });
});

This is the part of controller file (index.php) that handels the request:

        case "register":
        $email = htmlspecialchars($_POST["email"]);
        $username = htmlspecialchars($_POST["username"]);
        $password = htmlspecialchars($_POST["password"]);
        insertUser($email, $username, $password);
        break;

My problem is that the callback function is not invoked. Everything else works fine. Another strange thing is that the url string is changed from www.domain.com to www.domail.com/? even though the request is of post type. What am I doing wrong?

It sounds like you're submitting a form when you click the button, which will happen despite having code that also runs. Try this...

$("#registerButton").click(function(e){
    e.preventDefault();
    var email = $("#registerForm input[type='email']").val();
    var username = $("#registerForm input[type='text']").val();
    var password = $("#registerForm input[type='password']").val();
    if((!$.trim(email)) || (!$.trim(username)) || (!$.trim(password)))
        return false;
    $("#login").modal('hide');
    $("#login").on('hidden.bs.modal', function(){
        $.ajax({
            type: 'post',
            url: '?a=register',
            data: {
                "email" : email,
                "username" : username,
                "password" : password
            },
            success: function(){
                $("#test").html("Testing callback function");
            }
        });
    });
});

By adding e as a parameter in the click event handler and adding e.preventDefault() you can stop the default action of #registerButton , which in this case is probably submitting the form.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM