Alain Goldman
Alain Goldman

Reputation: 2908

Redirecting after Ajax post

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?

window.APP_ROOT_URL = "<%= root_url %>";

Ajax

$.ajax({ url: '#{addbank_bankaccts_path}',
 type: 'POST',
 beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
 dataType: "json",
 data: 'some_uri=' + response.data.uri ,
 success: function(APP_ROOT_URL) {
      window.location.assign(APP_ROOT_URL);
  }
});

Upvotes: 15

Views: 96600

Answers (3)

Madan Sapkota
Madan Sapkota

Reputation: 26111

You can return the JSON from server with redirect status and redirect URL.

{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}

And in your jQuery ajax handler

success: function (res) {
    // check redirect
    if (res.redirect) {
        window.location.href = res.redirect_url;
    }
}

Note you must set dataType: 'json' in ajax config. Hope this is helpful.

Upvotes: 13

backtrack
backtrack

Reputation: 8154

success: function(response){
    window.location.href = response.redirect;
}

Hope the above will help because I had the same problem

Upvotes: 22

kimbaudi
kimbaudi

Reputation: 15615

Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.

$('#checkout').click(function (e) {
    e.preventDefault();
    $.ajax('/post/url', {
        type: 'post',
        dataType: 'json'
    })
    .done(function (data) {
        if (data.cartCount === 0) {
            alert('There are no items in cart to checkout');
        }
        else {
            window.location.replace('/Checkout/AddressAndPayment');
        }
    });
});

Upvotes: 5

Related Questions