简体   繁体   中英

How to redirect after AJAX form submission with success callback function

I have a button in my form (not the submit) which triggers an AJAX call. I want the page to reload afterwards and reflect the new state (modified by the AJAX call). The AJAX call works fine, UNLESS I try to add a redirect at the end of the success: callback function. When the redirect is working in the callback, the page redirects and the AJAX call has had no effect.

It seems like the redirect is "interrupting" the AJAX call and not letting it happen, but that confuses me. I thought the success: callback only happend after the call is made. So how could things in that callback function interfere with things that should have already occurred?

Here's some HTML:

    <a href="http://example.dev/my-file-delete" id="deleteresume">Delete file</a>           

Here's my javascript:

    var deleteresume = function(event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "<?php echo $link_to_delete; ?>",
            success: hideresumefile( event.target )
        });

    }
    $("#deleteresume").click( deleteresume );
    var hideresumefile = function( target ) {
        $(target).closest('div').css('display', 'none');
        //THIS IS THE PROBLEM...
        $(location).attr('href', 'http://example.dev/handler.php');
    }

I've tried numerous variations of the redirect, for example:

window.location.replace("url");
window.location.href = "url";
location.reload(true);
window.location.reload(true);
location.href('url');
window.location.href('url');

When these work the AJAX call doesn't . What am I missing?

success: hideresumefile( event.target )

You are not passing the function, you are calling it here. This means that your hideresumefile function will actually run before the AJAX call...

success must be a function, to keep the same functionality, you could use:

success: function () {
    hideresumefile( event.target );
}

So you wrap the function call in another function, which is only defined, not invoked. It will only be invoked when the AJAX action is successful.

Wrap your hideresumefile call within a function.

var deleteresume = function(event) {
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "<?php echo $link_to_delete; ?>",
        success: function(result) { hideresumefile( event.target ); }
    });
}

$("#deleteresume").click( deleteresume );

var hideresumefile = function( target ) {
    $(target).closest('div').css('display', 'none');
    $(location).attr('href', 'http://example.dev/handler.php');
}

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