117

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.

Here is what I tried:

  var clicked = false;

  $(document).ready(function() {

    $("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true;  return true;");

    if (clicked == true) {
      // show hidden fields
    } else {
      // don't show hidden fields
    }
  });

Any suggestions on what is wrong with this code?

kryger
  • 12,906
  • 8
  • 44
  • 65
Neophile
  • 5,660
  • 14
  • 61
  • 107
  • 2
    I don't think this can be done without some kind of storage. Your JS variables will all be whiped clean. Your whole scope will be recycled. – Dave Alperovich May 05 '15 at 19:00
  • Why don't you put most of your page into a "partial" and refresh that? – Dave Alperovich May 05 '15 at 19:01
  • What is a partial? Sorry I am not aware of that. – Neophile May 07 '15 at 10:03
  • Have you considered submitting the form via ajax and showing the fields after the submission? – dannyshaw May 08 '15 at 12:24
  • Without sessionStorage, localStorage, or cookies. You're really going to need a server-side solution. – Downgoat May 09 '15 at 15:32
  • 1
    Can you elaborate on _why_ you need the page to refresh? If we can avoid it, you may able to do what you want if you just `preventDefault` on the `submit` event (instead of the `click` you're using.) – Peleg May 11 '15 at 21:29
  • I am actually looking in that direction of basically replacing the onclick with a return false and then setting the onclick to a callback function. I think it will definitely work this way. – Neophile May 12 '15 at 08:19
  • Some examples by passing data (encoding and decoding) to other pages: **http://stackoverflow.com/a/17309679/2247494** – jherax Feb 04 '16 at 18:12
  • Possible duplicate of [How to pass javascript object from one page to other](http://stackoverflow.com/questions/7709289/how-to-pass-javascript-object-from-one-page-to-other) – jherax Feb 04 '16 at 18:25
  • @Jhoverit Why did you feel the need to change the title of the Question? – guest271314 Nov 02 '17 at 20:02
  • It was an XY question title. The actual question is how to persist variables, not "Global Variable usage on document.readypage reload". Tho I can't believe I'm even being asked this given the old title hahaha –  Nov 02 '17 at 20:06
  • @Jhoverit The original title did not have any issues from perspective here – guest271314 Nov 02 '17 at 20:06
  • On a scale of 1 - 10 how would you rate your english? You type fine. But it should be obvious the old title was literally a kludge –  Nov 02 '17 at 20:09
  • If you really think "Global Variable usage on document.readypage reload" is a worthy question title... Idek what to say. You're entitled to that opinion, you can roll it back and see if it gets approved. –  Nov 02 '17 at 20:10

4 Answers4

236

As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.

There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript


Query string

When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:

<form method="GET">
    <input type="hidden" name="clicked" value="true" />
    <input type="submit" />
</form>

On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.

To read this data, you can use the following script on page load:

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, " "));
}

var clicked = getParameterByName('clicked');

(Source)

Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.

In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters


Web Storage

With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.

Here I set the storage on the button click event, but you could also bind it to form submit or anything else.

$('input[type="submit"][value="Search"]').click(function() {
    sessionStorage.setItem('clicked', 'true');
});

Then when you load the page, you can check if it's set using this:

var clicked = sessionStorage.getItem('clicked');

Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:

sessionStorage.removeItem('clicked');

If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.

//set
localStorage.setItem('myObject', JSON.stringify(myObject));

//get
var myObject = JSON.parse(localStorage.getItem('myObject'));

Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.


Cookies

An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.

You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.

$('input[type="submit"][value="Search"]').click(function() {
    $.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});

Then on page load you can read the cookie like this:

var clicked = $.cookie('clicked');

As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.

if(clicked === "true") {
    //doYourStuff();
    $.cookie('clicked', null);
}

(a non-jQuery way to set/read cookies can be found right here)

I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.


window.name

Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:

window.name = "my value"

It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:

window.name = JSON.stringify({ clicked: true });

The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.

This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.

Community
  • 1
  • 1
Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
  • 10
    Ugh, only after writing did I read your bounty description that said "no cookies or local storage". I'll keep this comment intact for others that might need it, but you'll just need to use the query string I guess. – Stephan Muller May 06 '15 at 08:37
  • It is quite a comprehensive answer and I am going to try out the query string approach. I've already tried out the local storage approach and that already works but I would prefer not to use that. I'll get back to you once I find it working. – Neophile May 07 '15 at 09:32
  • May I ask why you want to avoid localStorage? – Stephan Muller May 07 '15 at 10:40
  • 1
    Basically I am already using localStorage in a lot of cases for my web application and I would like to avoid using too many localStorage variables. However I do like the idea of removing the localStorage item once I am done with it. That was something I did not think of when using my localStorage variable. – Neophile May 07 '15 at 10:43
  • You could also consider saving multiple settings in one object, depending on how related they are to each other. – Stephan Muller May 07 '15 at 10:44
  • Using the query string method, is there a way I can find out what sort of call is being used when the submit button is pressed i.e. GET/POST? I don't control the form, its being controlled by the person who designed the website and I am just trying to do what I mentioned in my question. – Neophile May 07 '15 at 10:58
  • A POST has no visible query string – Stephan Muller May 07 '15 at 12:32
  • 3
    In case of post request you can modify the action -attribute $("#formid").attr("action", url+"&clicked=1") and also detect GET or POST from $("#formid").attr("method") but it may not solve how to detect the reload problem – Tero Tolonen May 11 '15 at 22:34
  • Ah, nice suggestion. Hadn't thought of that. – Stephan Muller May 12 '15 at 05:51
  • 2
    @TheNewbie it's been a while since I wrote this answer, but I just added a new option (`window.name`). It might just do exactly what you needed without using cookies/localStorage. – Stephan Muller Jun 04 '15 at 12:55
  • That's a good find you mentioned there. I will make sure I use the one I need. Thanks for keeping this space updated. – Neophile Jun 05 '15 at 13:45
  • 1
    I wanted to add that local and session storage are not totally reliable on newer browsers aswell. Usually there is a fallback to window.name. – JavaScript Jul 20 '15 at 11:34
  • Awesome answer +1!! I wrote some examples in another question: **[How to send variables from one file to another in Javascript?](http://stackoverflow.com/a/17309679/2247494)** – jherax Feb 04 '16 at 18:07
  • 1
    Great answer but this statement "According to the spec it should be possible to save other datatypes" (about web storage) ain't correct AFAICS. The storage interface is specified to be dealing with [DOMString](https://developer.mozilla.org/en-US/docs/Web/API/DOMString)s rather than arbitrary data types. For non-DOMString types it may be helpful to use [super-json](https://github.com/tarruda/super-json) to stringify more complex types. – Marcel Stör Mar 12 '16 at 10:24
  • @MarcelStör Thanks, to be honest I copied that line from another related answer without doing much research. I'll remove it and update with your info after actually doing some research on it :) – Stephan Muller Mar 13 '16 at 21:38
  • Can `window.name` method be used for an iframe as well? – Tushar Shukla Apr 29 '16 at 11:56
  • This answer helped me in choosing between which method to use for my dilemma I had regarding storage or cross page variables. +1 for the answer mate! – Syfer Jan 19 '18 at 06:47
  • Thanks, great answer. I went for the Web Storage over Cookies to solve my issue. +1 – Sam Jun 06 '18 at 15:44
  • The claim about statelenessness here is outdated; here in 2022, Firefox is automatically persisting control values when a page is reloaded with F5 or from within JS. Ctrl-F5 resets them. (Of no help if you have to get it working on other browsers, though.) – Kaz Jan 25 '22 at 19:15
  • Good addition, a lot can change in 7 years. Do you think I should adjust part of the answer? – Stephan Muller Feb 06 '22 at 21:44
5

Try utilizing $.holdReady() , history

function show() {
  return $("form input[type=hidden]")
          .replaceWith(function(i, el) {
            return "<input type=text>"
          });
}

$.holdReady(true);
    if (history.state !== null && history.state.clicked === true) {
       // show hidden fields
       // if `history.state.clicked === true` ,
       // replace `input type=hidden` with `input type=text`
       show();
       console.log(history);

    } else {
        // don't show hidden fields
        console.log(history);
    }
$.holdReady(false);

  $(document).ready(function() {

    $("input[type=submit][value=Search]")
    .on("click", function(e) {
        e.preventDefault();
        if (history.state === null) {
          // do stuff
          history.pushState({"clicked":true});
          // replace `input type=hidden` with `input type=text`
          show();
          console.log(history);
        } else {
          // do other stuff
        };
    });

  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
    <input type="text" name="name" value="" />
    <input type="submit" value="Search" />
    <input type="hidden" />
    <input type="hidden" />
</form>
Liam
  • 27,717
  • 28
  • 128
  • 190
guest271314
  • 1
  • 15
  • 104
  • 177
1

Using localeStorage or sessionStorage seems to be the best bet.

Intead of saving the clicked variable in the globle scope store it this way:

if(localeStorage.getItem("clicked") === null)
    localeStorage.setItem("clicked", "FALSE"); // for the first time

$(document).ready(function() {

    $("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");

    var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";

    localeStorage.setItem("clicked", clicked);

    if (clicked == "TRUE") {
      // show hidden fields
    } else {
      // don't show hidden fields
    }

});
me_digvijay
  • 5,374
  • 9
  • 46
  • 83
-6

You could try this:

 $("input[type='submit'][value='Search']").click(function(){
     form.act.value='detailSearch'; 
     clicked = true;  
     return true;
});
Downgoat
  • 13,771
  • 5
  • 46
  • 69
renakre
  • 8,001
  • 5
  • 46
  • 99