Redirect after Ajax post

I want the ajax post to be able to go to the main 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); } }); 
+7
jquery ajax
source share
3 answers
 success: function(response){ window.location.href = response.redirect; } 

Hope this helps, and I had the same problem.

+13
source share

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

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

And in your jQuery ajax handler

 success: function (response) { // redirect must be defined and must be true if (response.redirect !== undefined && response.redirect) { window.location.href = response.redirect_url; } } 

Note that you must set dataType: 'json' in the ajax configuration. Hope this is helpful. Thanks!

+6
source share

I don’t know why, but window.location.href did not work for me. I ended up using window.location.replace , 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'); } }); }); 
+5
source share

All Articles