Maurice
Maurice

Reputation: 1157

Using location.href= with click function, prevents my form to submit

I have a form with the following button:

<input id="test2" class="formbutton" type="submit" value="Play again" />

Pressing the submit fires this javascript:

$("#test2").click(function(){
        $.ajax({   
            type: "POST",
            data: $("#form").serialize(), 
            cache: false,  
            url: "insert.php"  
        });   
        return false;
    });

This all works fine. The problem is when I try to ad location.href="mahjong.php?layout=win"; What I want is that when I press this button, the form is submitted and loads the url mahjong.php?layout=win

If I use:

$("#test2").click(function(){
location.href="mahjong.php?layout=win";
$.ajax({   
            type: "POST",
            data: $("#form").serialize(), 
            cache: false,  
            url: "insert.php"  
        });   
        return false;
    });

I go to the url but the form is not always submitted. How to fix this. I cannot edit the insert.php file since this one is used by other buttons too (where no redirection is needed)

Upvotes: 0

Views: 2587

Answers (3)

Alnitak
Alnitak

Reputation: 339816

As soon as you set location.href the current page will be unloaded and all scripts on it will stop.

Use a (deferred) completion handler:

$("#test2").click(function () {
    $.ajax({
        type: "POST",
        data: $("#form").serialize(),
        cache: false,
        url: "insert.php",
    })
    .then(function() {
        location.href = "mahjong.php?layout=win";
    });
    return false;
});

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237865

Go to the link after the form has returned, using a success handler:

$("#test2").click(function () {
    $.ajax({
        type: "POST",
        data: $("#form").serialize(),
        cache: false,
        url: "insert.php",
        success: function () {
            location.href = "mahjong.php?layout=win";
        }
    });
    return false;
});

It's probably worth putting some visual notification on the page, e.g. a spinner or disabling the button, so that the user knows something is happening and doesn't click the button again.

Upvotes: 3

Billy Moon
Billy Moon

Reputation: 58531

put the location.href after the ajax call, otherwise you might leave the page before the ajax call has been sent.

If that does not work, put the location.href in a callback function of the ajax call, so it will load a new page after you get a response from the server, so you can be certain that the data has been sent.

Upvotes: 0

Related Questions