michaelAdam
michaelAdam

Reputation: 1137

How do I call a function after a redirect or refresh?

$('#submit').click(function(){
        window.location.replace("searchscreen.html");
            var term = $('#search').text();
            displaySearchEntries(term); 


        });

I am writing code to direct to a search results page and to call the javascript function to return the appropriate results. As of now, this redirects the page, and displaySearchEntries(term) gets called, but disappears immediately. It seems as if the redirect happens after the call to the function, but I don't know why that would be happening or how to prevent it. Any suggestions?

Upvotes: 0

Views: 4883

Answers (3)

Yasitha
Yasitha

Reputation: 2303

When you use window.location it kills all the scripts running in the browser. You can use JQuery AJAX call and use the callback function to do the rest.

If you don't won't to use the AJAX function the only possible way to do this is use a parameter to identify the redirection.

window.location = "searchscreen.html?redirect=true";

And check the redirect variable and call the function in the $(document).ready().

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You can not control the next page. Once the redirect happens, that page is done.

If you want something to happen on the next page you will need to find a way to pass info to that page. That is normally done with a querystring, posting a form, cookies, or local storage. The next page would need to look for that data and process it.


Basic idea using querystring:

First page:

$('#submit').click(function(e){
    e.preventDefault();
    var term = $('#search').text();
    window.location.replace("searchscreen.html?search=" + encodeUriComponent(term));
});

and code on the searchscreen.html

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(function(){   
    //read querystring
    var term = getParameterByName("search");
    //run your search
    if(term.length) {
        displaySearchEntries(term);
    }
});

Upvotes: 1

user123
user123

Reputation: 31

Call function on the redirected page.In search screen.html use document.ready

Upvotes: 0

Related Questions