David Corbin
David Corbin

Reputation: 514

Stopping redirect after AJAX request with jQuery

I'm trying to get a simple form to submit via AJAX to the submit.php page where it is sent to a database. When I submit it, it redirects to submit.php. I want it to submit without redirecting. Thanks in advance!

JS

var request;
$("#myForm").submit(function(event){
    if (request) {
        request.abort();
    }
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    request = $.ajax({
        url: "/submit.php",
        type: "post",
        data: serializedData

        //Could something like this work? 
        //complete: function() {***Stop redirect?***}



    });

    request.done(function (response, textStatus, jqXHR){
        console.log("Hooray, it worked!");
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
        $inputs.prop("disabled", false);
    });

    event.preventDefault();
});

Upvotes: 1

Views: 4326

Answers (2)

Henry Blyth
Henry Blyth

Reputation: 1750

Is the document ready when your code runs? If not, $("#myForm") is returning an empty jQuery object, therefore any handlers attached to it won't ever be called. Test this by saving the jQuery object to a variable and logging it to the console.

Two solutions:

  • Move your code into a document ready handler: $(function () { /* my code dependent on DOM elements */ });
  • Use an event listener instead of binding to elements: $(document).on('submit', '#myForm', function (event) { /* handler */ }

There's nothing wrong with the event.preventDefault(); line - it can stay where it is, although I prefer to place it at the very top unless it's part of a conditional - and return false; isn't needed.

Reason I can answer this: I just setup a local test for this and came across the same problem: my submit handler wasn't running at all. But then I realised my <script> tag was before the #myForm element but my code wasn't waiting until #myForm was in the document before trying to find it with $().

Edit: Placing the <script> tag at the bottom of the <body> negates the need to wait for document ready in your case. It also speeds up page rendering, but that's a whole other discussion.

Upvotes: 1

DarkseidNG
DarkseidNG

Reputation: 92

Put the event.preventDefault(); right after the first code line the one with the .submit listener

Upvotes: 0

Related Questions