How do I pass a variable like username between two jQueryMobile pages?
or two regular pages for that matter, having the variable as global does not work, since at th
You may store variables for global usage the same way JQM stores its own configuration. Just create your own javascript object under $.mobile at 'mobileinit' and use it for your global variables:
<!DOCTYPE html>
<html>
<head>
...
<script> // position before jquery.mobile.js is important for 'mobileinit' to fire
$( document ).on( "mobileinit", function( event ) {
//create global variable storage
$.mobile.YourApplicationNameHere = {};
//use it like this anywhere in your code:
$.mobile.YourApplicationNameHere.globalVar1 = 1;
$.mobile.YourApplicationNameHere.globalVar2 = 2;
console.log("globalVar1 = " + $.mobile.YourApplicationNameHere.globalVar1);
});
</script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
...
</head>
...
</html>
You may initialize your global variables anywhere, but 'mobileinit' is the earliest initialization point of JQM.
You can use either the URL through a query string or client side routing, you can use localStorage (assuming they are on the same domain), or you can use cookies.
If you decide to use client side routing there is a plug in specifically for JQM that ties in with the different JQM page events
https://github.com/azicchetti/jquerymobile-router
I usually go with local storage, you can store objects too. Ex:
var userInfo = {
"username": "Bob",
"roleName": "Admin",
"image": "img/userPic.jpg",
};
//Store the object in local storage
localStorage.setItem('loggedUser', JSON.stringify(userInfo));
then on the other page you can simply do:
var userInfo = JSON.parse(localStorage.getItem("loggedUser"));
var userName = userInfo.username;
You can pass it in the query string as long as you disable ajax on the hyperlink between the two pages.
<a href="nextPage.php?username=joe" data-ajax="false">Next page</a>
You miss out on the beneficial features of jQuery mobile transitions, but at least you can successfully pass variables between pages.
Update:
From the documentation:
Passing parameters between pages:
jQuery Mobile does not support query parameter passing to internal/embedded pages...
The documentation then goes on to suggest two plugins which I have not tried. Page params plugin and jquery mobile routing plugin.
Be sure to check out the documentation page linked above for their explanation on why passing parameters shouldn't work but if you load the page without the hashing (by disabling the ajax behavior) then you should be fine -- at least in my experience.