Passing data from one page to another - javascript

Pls can anybody give me the clue of how to pass data from one page(test1.html) to another page(test2.html) and then later pass the previous 2 pages(test1 and test2.html) to a new page called last.html using javascript not php cos it is a local app. tanx

There are several ways to do it, you could pass a query string from page to page (prob a bad idea unless we are talking small bits of data you dont mind people seeing)
You could use local/session storage depending on the browsers you are looking to support.
You could also use a database and have a ajax post/get from page to page (not a great idea)
If you have something like php in the back end you could use a php session.
You could also use a cookie (again not the best idea but a good fallback for local/session storage)
Or you could have a single page app and use something like angular to show/change your page(s)

Related

How to get the values of session using js

I want to know if the user has logged in or not and then display different elements of the navigation based on the username (login by email and password Not username). However, I have no idea how to deal with session. If php and html is separated in two documents, how can I store the required values using session in php document and then get them using javascript in html document? Or should I use cookies instead?
There are a several approaches to do this.
1) You can make a PHP file which will format your $_SESSION data, and all the other data you want as a JSON string (json_encode function in PHP lang). Then use echo to return it. Then use an AJAX request to get this file from javascript or JQuery, and you will receive the data you want. That's a bad approach for this purpose, from my point of view, because after loading the page you send another request to receive a static data, which will not change on the page like email or username.
2) Better approach: PHP is preprocessor hypertext. You can make an php file and write html tags in it, with php output(example: <div><?=$_SESSION['email']?></div>). Search for more info in google ("php inside html").
3) Much better. In modern web programming world its a mistake to use php inside html because you should think not only about how to make something work, you should think how you will maintain it after 3, 6, 12 months later, too. If you use just php inside html in a big project, then, with time, you realize that your code is hard to read and looks ugly. There are plugins that can make your view more readable and maintainable (Twig, Blade, Volt and others). I recommend you use one of them.
The session is a server side thing, you cannot access it using javascript. You can write an Http handler (that will share the sessionid if any) and return the value from there using AJAX

Persist Local UIWebView Values

*EDIT*
I've done more research and it looks like cookies may also be the answer. I suppose I would add a button to the form inside the embedded html that calls a function to create a cookie for the values. Then I could access this cookie through obj-c using the stringByEvaluatingJavaScriptFromString method. Of course then you run into the issue of expiration, multiple copies of the form not being allowed, etc. So it is a trade-off of features. I'm going to stick with the window.location route because I can store this in a DB and then the user can create another instance of the same form
*EDIT*
I've done some research and I have a vague idea how to accomplish this, but I was curious if there was a better method.
I have a local copy of an html form loading in a UIWebView on this iPad app I am developing. The forms are submitted server-side through xml and parsed there for DB storage, but unfortunately they are pretty lengthy. So I want to let the user save the form in its current state (maybe they only fill it out halfway), and then return to it later.
What I am thinking is that I will have to write some javascript to parse the radio buttons and checkboxes in the form, then pass this data through the window.location trick to the obj-c code. But this is VERY lengthy, and the strings being passed back and forth between JS and Obj-C will be very long. Is there any other way to grab the values of these checkboxes/radio buttons and pass them to the obj-c side to be repopulated later?
How about going via a file? Save the settings/data to a file in JS and access that file in Objective-C land. But I guess you've already thought of this.
But at the end of the day the data has to be passed back and forth regardless of how you do it. Doing it via the window.location trick will be the fastest, and provided there are no limitations imposed by the OS itself is there any reason not to do it this way?
You could encode the data into a blob to make it easier to pass around.
But on the other hand doing it by file route may however be useful if you want the settings to persist if your app gets terminated.
Also you could actually submit the form data but intercept it in Objective-C before it gets sent by using a NSURLProtocol derived class. THe NSURLProtocol class could allow the submission to proceed if it knows the data is complete. But I don't see any point in doing this if window.location doesn't have a size limit.

best way to send JSON to the page at creation time

I need to send some data to a web page, ideally in json format and I wonder what method is considered best, and why. Overall what good or bad experiences and surprises you had with them.
<script>var myJson = <? echo json_encode($myVar);
?>;</script>
advantage: the json is directly in javascript, were it will be used.
inconvenient: <script> in the middle of html/dom is bad (js belong
to .js files).
<div data-myJson='<? echo json_encode($myVar); ?>'>
advantage: html5 data thing is easy to work with. inconvenient:
bunch of data in the dom, it doesn't look elegant note: in my
case, I can afford to ignore "old" browsers.
ajax everything.
advantage: the json doesn't even need to be sent in this case, as it
will be already available (no page change). inconvenient: not
really an option as I would need to rewrite the full website.
instead of sending the full json, store it in the session and send a
key.
advantage: less data moving around inconvenient: the
data/session couple needs to be kept track of, and I like my session to be kept clean and tidy. (even if user just close the page before the flow is
finished) (which won't close the session).
Cookies.
advantage: herr.. is reverse evil a good thing? inconvenient: like session variables, but out of the cage.
Store the json in the session, and ajax it when the page is loaded.
advantage: somewhat elegant conceptually. inconvenient: heavy, as the ajax instruction has
to be added to a js file, and the session has to be managed. (and
cleansed. if the page load doesn't finish, the json will stay until
I cleanse it or the session finishes). Plus the html header means more bandwidth, and the we have to wait for the success to use the object.
other?
edit: as there seems to be a bit of confusion, with option 3 "ajax everything" I was meaning one page load, and all content loaded by ajax, even if you go through menus, links to other pages, forms submit, and such. I consider a more traditional navigation, (pages sent by the server as new a pages), with a page doing an ajax request to retrieve some value (here, my json object) on the server, as point 4 "session", as the main data has to remain on the server after the page has been sent to be later fetched by the ajax request. I did add option 6 for this.
I unhesitatingly recommend #1. You want to use your data in javascript, right? #1 is the simplest way and most direct way to ensure that your data exists, as a plain-old javascript object, when the page loads. I transfer data from the server side to the browser side all the time this way and it works beautifully.
You could arguably create better separation between your data and your UI by loading your data in an ajax call, but this is an additional http request, which will slow your page load.
Been a few years since this was asked, but for anyone else who finds themselves here and curious, I've been doing a variation of option #1 for quite a while. Additionally, Nike Plus does this as well. When the page loads, Nike sets window.np = {}
I've never really found a convention I love, but I've tried:
window.data
window.app.data (inspired by Symfony, literally uses the attribute app)
window.[app_name].data (inspired by Nike Plus)
window.initData (inspired by Google+)
In my case, I overwrite these JS objects with Backbone models/collections when the main Backbone app loads.

HTTP cookie between two HTML pages

I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.
When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.
Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?
I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.
If some one has a better solution please let me know. Thanks
try to use localStorage instead of cookies,
// set your values in the first page
localStorage.setItem('itemKey', 'values');
// on the second page, retrieve them
var values = localStorage.getItem('itemKey');
you can use a jStorage plugin for cross browser behaviour.
also refer to this question for storing objects instead of strings
JAAulde is on point with his answer.
For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.
Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.

Changing Javascript History

When I load my php page I append some data. For instance MyPage.php?value=something.
As expected, when I go back and forth using the back button, it always loads with that same data appended. I don't want that. I want that after the page loads, I should be able to change the history to store only MyPage.php WITHOUT the appended data.So now when I would use the back button it would load MyPage.php only. How can I do this - javascript, jquery, php , anything???
If there is a way to do that without touching the history object, thats also fine. I'm just assumng it'll take some history tweaking. I'm also OK if it takes tweaking on the client or server side.
As far as I know, it is not possible to tweak the history like that, nor is it a good way to deal with this.
You could use a cookie to determine when a page gets loaded more than twice, or store the data in a session variable instead, and delete it once your processing is done.
I assume the data is appended by using GET method. Using POST will not append text after MyPage.php but still can pass data to the page.
The history is the history. It's a bit of a hack to go changing that (and you will probably have other issues down the road if you do).
It is better to either have NO querystring at all, and use js or server-side logic to determine the action, or to have js or server-side logic to ignore the second request.
If you are fine with tweaking the history then you can probably look in to this.
history.replaceState({}, document.title, "MyPage.php");
This will rewrite the current window.location to "MyPage.php" without page refresh.

Categories

Resources