Let's say I have a page that refers to a .js file. In that file I have the following code that sets the value of a variable:
var foo;
function bar()
{
foo = //some value generated by some type of user input
}
bar();
Now I'd like to be able to navigate to another page that refers to the same script, and have this variable retain the value set by bar(). What's the best way to transport the value of this variable, assuming the script will be running anew once I arrive on the next page?
You can use cookies.
Cookies were originally invented by
Netscape to give 'memory' to web
servers and browsers. The HTTP
protocol, which arranges for the
transfer of web pages to your browser
and browser requests for pages to
servers, is state-less, which means
that once the server has sent a page
to a browser requesting it, it doesn't
remember a thing about it. So if you
come to the same web page a second,
third, hundredth or millionth time,
the server once again considers it the
very first time you ever came there.
This can be annoying in a number of
ways. The server cannot remember if
you identified yourself when you want
to access protected pages, it cannot
remember your user preferences, it
cannot remember anything. As soon as
personalization was invented, this
became a major problem.
Cookies were invented to solve this
problem. There are other ways to solve
it, but cookies are easy to maintain
and very versatile.
See: http://www.quirksmode.org/js/cookies.html
You can pass the value in the query string.
When the user navigate to the other page append the value to the query string and load it in the next.
Another option is jStorage. jStorage is probably better used for cached data and lossy user preferences (e.g. saved username in a login form), as it doesn't have full browser support (but IE6+ and most other common browsers support it) and cannot be relied upon (like cookies).
You can use YUI's Cookie Library http://developer.yahoo.com/yui/cookie/
Related
I'm trying to determine the best way to cache my JavaScript and CSS files.
There are several ways of doing this:
Using the Date, Expires and Cache-Control headers
Using the ETag header
Cache forever and change the filename when the file changes
Append a querystring to the filename in the HTML with the last mod time or an MD5 of the file contents
I was under the impression that the last method (4) was the most reliable and would result in the fewest unnecessary requests, but my friend just told me that sometimes the querystring method is unreliable and you actually need to change the filename.
Are there any downsides to setting the HTTP headers to cache forever and just using a query-string with the last mod time, or are there scenarios where another method would be more beneficial?
I'm a big fan of method 4, but I use the Session Id, on it. So, a user that enters my website will load it once per session (a session usually dies if the visitor keeps inactive for more than 20 minutes or if he closes the browser window).
In Asp.net, I use that syntax:
<script src="js/DetalhesCurso.js?<%=Session.SessionID%>"></script>
Your third method is the most reliable. Some CDNs/proxies ignore the query string altogether, and just serve the same cached file regardless of the query string value.
Amazon and Azure do support it, but others might not.
Do note that in method #3 you don't actually have to update the filename itself. You can just use some URL rewriting to always get that same file. You'll only have to update your HTML.
I'm looking for the best practice here.
I need to store 10 variables of information, in a certain format:
lname: [John]
fname: [Doe]
etc...
using Javascript. I was thinking about using cookies.
My scenario is as follows:
The user would be in Salesforce.com and they would enter the customer's information into a record. They would then click a button get a quote. The button, using JS, would write the Salesforce fields to a temp file (cookie maybe). From there the other MS application would pick up that file and read in the values.
How would you guys do that?
Thanks for the time.
The browser will not allow you to write files, generally speaking. For this, you'd have to use a mechanism to get out of the security sandbox, such as a signed Java applet.
Cookies are NOT a good option here. Desktop apps should not be attempting to access browser cookies; at best, it's considered "badly behaved code"; at worst, you won't be able to do it, or your app will get detected as malware. Even if it was considered OK, you'll have to write cookie-reading implementations for any browser you want to support since there is no standard for how they are locally stored.
Why not make the desktop app access the web on behalf of the user? Write SFDC quote requests to a new SFDC custom object, like Quote_Request__c or similar, and the app can query the most recent record(s) created by the user via the API.
Clipboard integration, while it sometimes seems clunky, may be a low-cost option.
If you must write to a local file of some sort, you'll need to use Flash or Java, or make the user locally save some downloaded file (like any normal browser download).
Another option would be to register your desktop app as a URL protocol handler; so, say, myquote://firstname/lastname/product/price/etc could be clicked from a web browser to launch the app and parse the "URL". May work poorly with very long/complicated data though.
Yes, cookies are certainly an option in this case. Cookies are accessible via the document global object (e.g. document.cookie). It can hold a string and an expiration date.
Here is a cookie handler I wrote:
http://jsfiddle.net/zbaJz/1/
Using this handler, you can store information in a cookie, and would be able to view as well as delete it. Then, using JSON stringify, you can pass it an object.
var name = {
'fname': 'John',
'lname': 'Doe'
};
var jsonText = JSON.stringify(name);
var cookieMonster = new Ovenmitts();
cookieMonster.bakeCookie('name', jsonText);
Then, in order to turn the data back into an object to manipulate, you would use JSON.parse.
var cookieInfo = cookieMonster.admireCookie('name');
var revived = JSON.parse(cookieInfo);
You can add a thread/task to the MS Application that watches for changes in the directory whee the cookie is created. When you detect a new file that meets your requirements you can act on it. You will need to use DirectoryInfo for this approach.
You can also create and windows or webservice that the application listen to and can pass the data this way from the web app.
I recently received a request to determine if a user's browser has pre-fetching enabled. I've searched around, but I've come up empty. Any thoughts on how to accomplish this task? I've watched traffic in the header and I don't see anything in the request that would indicate pre-fetching has been enabled.
Put <link href="myTester.xxx" rel="prefetch" /> in the head.
In whatever handles for myTester.xxx (which would hence more likely by myTester.php, myTester.aspx, etc.) set a flag in the session (if you're already using sessions and hence there's no more penalty for doing so) or set a cookie. Make the response v. small (empty would be fine).
On onload, set a delayed (use setTimeout) attempt to retrieve an XML or JSON file from myTesterResult.xxx which has a different result depending upon that session value or cookie.
Alternatively, if you don't need it to be reacted to on that page, there's no need for any client-side script at all, subsequent server-side script will be able to use the session or cookie as appropriate.
I'll 2nd the opinion that the client probably can't do it. One possible solution is to add a prefetch to a page that signifies pre-fetching is enabled, e.g.:
<link rel="prefetch" href="/hasPrefetching.php">
If you need to know on the server, you now have the info. If you need to know on the client, you can poll for it after a while.
If JavaScript is disabled what's a way of linking to the previous document in the session history?
Can PHP be used to simply link to the REFERRER or is there a better alternative?
Edit: Further to this, can previous post variables be retained?
You're really mixing the idea of previous document in client session history vs. server session history.
Since Javascript is client-side, executing a history.back() renders the control to the browser, which then decides which page was last in the history (keeping in mind that the last page may not be a page within your domain). When you're using server-side PHP, the HTTP header referrer is whatever the browser supplied to you. If your server-side URI wasn't called as a result of an explicit click on a link, form GET/POST, etc. , your script probably won't get a referrer header value.
If you only want to capture the referrer within your site's domain, you can start maintaining a breadcrumb trail server-side (in the user's session). eg: $_SESSION['breadcrumbs'] = array( 'page1', 'page2', ... )
POST variables can be persisted in the SESSION too though I've never seen a good reason to do so. If you're trying to return an error message for a form and expect to get back the POST, you shouldn't be saving the state of the original POST.
ASP .NET is allowed
Storing the values in hidden input fields is allowed
Query String is not allowed
POST request is not allowed
It is possible to store JS variables between GET requests ?
I want to reinitialize them on the client using ClientScript.RegisterStartupScript
Can I use cookies for this ?
Are there other posibilities?
Where cookies are stored when Request is made ?
Can I use cookies for this ?
Yes, see this tutorial on using cookies in Javascript.
Are there other posibilities?
If you are not allowed to append anything the URL of your requests, I can't come up with any.
Where cookies are stored when Request is made ?
In the HTTP request header. The aforementioned tutorial will tell you how to read their values from Javascript. On the server side with ASP.Net, you can read cookie values using Request.Cookie["cookieName"] which returns an instance of HttpCookie.
I wouldn't highly recommend this, but the other option is to alter the window.name property.
You can save some minor bits of data here, then retrieve them on the next page load.
Pros:
Quick-n-dirty, but works
Cons:
Messes up any window references for popups/child iframes
Since its a "hack", browser vendors may break this "feature" in the future
Of course if you can exclude all the old browsers, then use Global/Client Session Storage!
At the moment using cookies is your best bet. You can serialize the JavaScript objects to strings, and unserialize them back into objects later. A good choice format is JSON, since it is a subset of JavaScript.
There is also storing objects in Flash.
Storing in Google Gears.
DomStorage
See this library that has an interface to each:
http://pablotron.org/?cid=1557
If you are in control of all aspects of the page, then you can also wrap the page in a top level frame. Then only refresh the child frame. You can then store content in the parent frame.
You can see this used in sites like GMail, and others where the only thing that changes in the URL is outside the #.
You don't even have to change the URL, that part is just put in for Human Friendly URLs. (So you can actually copy and paste URLs as is).