user2166538
user2166538

Reputation: 313

AJAX signup form with PHP failing

My websites signup for script is below. When a user clicks signup, it sends all the data to another page through AJAX, if it is successful, it is supposed to change the page, however, it seems as soon as I call the function, the page reloads to the homepage with top.location.href = '/'; instead of waiting for success of the AJAX call.

What am I doing wrong and how could I fix it?

<script>
    $("#button").click(function() { 
        username = $('#loginNames').val();
        password = $('#passwords').val();
        email = $('#email').val();
        q = $('#q').val();
        a = $('#a').val();
        name = $('#i7').val();
        jQuery.ajax({
            type: "POST",
            url: "signupprocess.php",
            data: {'username':username, 'password': password, 'email': email, 'q':q, 'a':a, 'name': name},
            cache: false,
            success: function(response) {
                if(response === up) {
                top.location.href = '/';
                } else {
                    $('#response').html(response);
                }
            }
        });
        return false;
    });
</script>

Upvotes: 1

Views: 225

Answers (1)

Nabil Kadimi
Nabil Kadimi

Reputation: 10394

I see 2 problems with your code:

1st Problem

You need a preventDefault(), just add it anywhere in your click() function

So:

$("#button").click(function(){  

Should become

$("#button").click(function(e){  
    e.preventDefault();

From the method documentation:

If this method is called, the default action of the event will not be triggered. - event.preventDefault()

So in your case, your code doesn't cancel the default button behaviour unless you add a preventDefault()


2nd problem (not an answer though)

You shouldn't use click on the button, you should use submit on the form, this way you catch the form submit whatever the triggering event was, the user could submit the form by pressing enter, I do it all the time and I bet this is what you do too.

Upvotes: 3

Related Questions