Will Ashley Will Ashley - 7 months ago 47
Javascript Question

Ajax wait till redirect to finish executing.

I have basically the same problem as the one described in the link below, but I dont find the solution to be very clear. I want my ajax success function to wait until the window function is finished executing, THEN modify the divs. Instead, it modifies the divs of the current page, then redirects. AJAX: on success redirect then modify new page

main.js

$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',


success: function(data) {

//Redirect to the page where we want to display the data
window.location.href = '/test';


data = JSON.parse(data);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);


},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});

});

Answer

I Will Suggest you Javascript Local Storage .

main.js

$("#form").submit( function(e) {
    e.preventDefault();
    var id = $('#searchbar').val(); // store the form's data.   
        $.ajax({
                url: '/search',
                type: 'POST',
                data: {id:id}, 
                dataType: 'text',


            success: function(data) {

                //Redirect to the page where we want to display the data
                window.location.href = '/test';


                data = JSON.parse(data);
                console.log(data);
                // Store
                localStorage.setItem("count", "we analyzed...");
                localStorage.setItem("result1", data.county);
                localStorage.setItem("totals", "with a score of..");
                localStorage.setItem("result2", data.totalSentiments);

   },
   error: function(jqXHR, textStatus, errorThrown){
     console.log("error")
     alert(textStatus, errorThrown);
  }
});

});

On Ready on same page:

jQuery(document).ready(function(){
    if (localStorage.count) {
        $("#count").text(localStorage.count);
    }
    if (localStorage.result1) {
        $("#result1").text(localStorage.result1);
    }
    if (localStorage.totals) {
        $("#totals").text(localStorage.totals);
    }
    if (localStorage.result2) {
        $("#result2").text(localStorage.result2);
    }
});

Local Storage Store Data in Browser Storage. You Also Can Remove Data From Local Storage.