6

I need to redirect to another page onClick of submit and call a function making an ajax call. This is what I have :

$('#submitButton').click(function() {

window.location.href = "otherPage";
displayData();
});

Also, Another way I tried is to set the form fields on otherPage by using

var elem = window.document.getElementById(field);
elem.value = "new-value";

so that I could call the eventhandler of a submit button present on otherPage, but it doesn't work. Please let me know where I am wrong.

SKaul
  • 349
  • 2
  • 7
  • 22
  • 1
    I don't think displayData() would work after redirecting. – Bhojendra Rauniyar Feb 19 '14 at 08:56
  • 1
    You have to include `displayData()` to the target page and call it when loaded. – Teemu Feb 19 '14 at 08:57
  • displayData is already included in the target page, I can call it from there, but I am not able to call it in the way I described. – SKaul Feb 19 '14 at 09:11
  • @SKaul You know you can keep only one page at the time on a window? Setting `window.location.href` loads _a new page_, and _all_ the code in the current page is replaced with code of the new page, including the function call after setting the `href`. On the other hand, "`otherPage`" doesn't exist before it is loaded to a browser (before loading it's just a file on a server), hence any submit handler doesn't exist either. If you have this "`otherPage`" opened in another tab, pop-up or iframe, then it's possible to call a function in it. – Teemu Feb 19 '14 at 15:49
  • I added an alert instead of the function call, it worked. How did that happen ? – SKaul Feb 19 '14 at 19:50
  • 1
    Most likely you've added the alert before redirecting, or that other pages alerts you... – Teemu Feb 19 '14 at 20:04

2 Answers2

8

I'm not sure if there is a neat way to achieve this, but you can add a hash in your url you redirect to, then just simply check if the hash exists, execute function and remove hash.

Here are some handy URLs:

Community
  • 1
  • 1
Arko Elsenaar
  • 1,689
  • 3
  • 18
  • 33
4

A hash (as Arko Elsenaar said) or a querystring parameter added to the target URL would allow you to detect what to do once there. The hash makes it a bit easier while the querystring is cleaner if you want to pass more information.

For instance on the first page: window.location.href = "other/page.html#displayData";

On the second page:

if (window.location.hash === '#displayData') {displayData();}

Another way could be to use the HTML5 Storage API, if and only if the 2 pages are on the same domain.

1st page would do, before the redirection: localStorage.displayData = true And the 2nd: if (localStorage.displayData) {displayData();} However in this case you'll need to clean up the localStorage.displayData value when used, otherwise it will stay there forever and your second page would always find it set to true. delete localStorage.displayData

All in all, the hash method seems best here.

Greg
  • 3,370
  • 3
  • 18
  • 20