Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters while changing the page in JQuery Mobile?

I've searched around stackoverflow but didnt find a proper solution to programmatically change the jqm page and pass a (get) parameter with it. I'm new to jqm so maybe I get something wrong on passing data with the changePage() function.

using jquery mobile 1.1.1 and jquery 1.8.0

I have a list and want all items to point to the same #profile page. on that page I want to load the appropriate data with ajax/json.

<ul data-role="listview" data-theme="a">
   <li><a href="#profile">Martin</a></li>
   <li><a href="#profile?id=2">Johnny</a></li>   
   <li><a href="#" onclick="changePage()">Luke</a></li>
</ul>

The first link working, but no id is passed (obviously)

The second link ist not working throws exception (in chrome): Uncaught Error: Syntax error, unrecognized expression: #profile?id=3

The third link uses this function:

function changePage() {
            $.mobile.changePage("#profile", { data: {id:1} });
            //alert('page changed.'); 
            return false;
        }

It changes the page but the url is basefile.html?id=1 but it should be basefile.html#profile?id=1

Can anyone help with that? Thanks a lot.

like image 952
LukeSolar Avatar asked Aug 21 '12 15:08

LukeSolar


2 Answers

As mentioned in the jQuery Mobile Docs, jQuery Mobile does not support query parameter passing to internal/embedded pages but there are two plugins that you can add to your project to support this feature. There is a lightweight page params plugin and a more fully featured jQuery Mobile router plugin for use with backbone.js or spine.js.

There are other ways to implement the data passing during different pages but some of them may are not supported from old web browsers. You will have to select your implementation way carefully so that it does not induce consequences to the application's interoperability over multiple browsers.

You can pass data between different pages by using the Web Storage.

As mentioned in the W3schools site, with HTML5 web pages can store data locally within the user's browser. Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance. The data is stored in key/value pairs, and a web page can only access data stored by itself. Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari. Internet Explorer 7 and earlier versions, do not support web storage.

There are two objects for storing data on the client:

  • localStorage which stores data with no expiration date
  • sessionStorage which stores data for one session

Examples:

Local Storage Example:

In Page1: localStorage.carType="test";
In Page2 you can retrieve the carType using: localStorage.carType

Session Storage Example:

In Page1: sessionStorage.carNumber=10;
In Page2 you can retrieve the carType using: sessionStorage.carNumber

Regarding your case, a possible solution is to add ids in each anchor. Then catch the click event, retrieve the id, save the id in the web storage and perform the page transition. In the next page retrieve the id from the web storage. Below you can find the implementation:

<ul id="menu_list" data-role="listview" data-theme="a">
   <li><a id="1" href="#">Martin</a></li>
   <li><a id="2" href="#">Johnny</a></li>   
   <li><a id="3" href="#">Luke</a></li>
</ul>


$('#menu_list').children().each(function(){
    var anchor = $(this).find('a');
    if(anchor)
    {
        anchor.click(function(){
            // save the selected id to the session storage and retrieve it in the next page
            sessionStorage.selectedId=anchor.attr('id');
            // perform the transition
            changePage();
        });
    }
});

EDITED:

Alternative way to pass parameters when following a multiple pages approach

This example uses jQM changePage() to send data with an Ajax page request.

$('#list-d a').on('click', function(e) {
    e.preventDefault();
    $.mobile.changePage('car-details.html', {
        data: {
            id: this.id
        }
    });
});

The constructed URL is .../car-details.html?id=my-id

For a complete example check this StackOverflow answer

I hope this helps you.

like image 82
Apostolos Emmanouilidis Avatar answered Oct 13 '22 22:10

Apostolos Emmanouilidis


I see that this question was already answered and comments were traded on the answer, and I have also faced this issue. Using jQuery Mobile as it is intended allows for ajax loading, and therefore no need for a browser refresh unless instigated by a user, correct? And if a user is refreshing for some reason, that means that the site or app isn't functioning the way it is exptected to since most users wouldn't refresh without a frustrating cause.

In saying so, as suggested by the comments creating a variable is an efficient way of passing data from "page" to "page". However, my suggestion in doing so is to instead create a global variable to contain site information.

$('#elemControlToChangeBy').on("tap", function(oEvent)
{
   oMyNameSpace.PageDataObj = oDataObj;

   $.mobile.changePage("#elemPage", {transition : "type"})
});

$("elemPage").on("pageshow", function()
{
   var oDataObj = oMyNamespance.PageDataObj;

   //Use the data...
});

Obviously the code will have to modified to your coding conventions, but the concepts are there:

  • Store your data or access it by some other means
  • Place the data in a contained variable to prevent any overwrites by external code
  • Access the data object variable when you arrive at the next page

There are other routes, as already stated(local storage, ect) so I won't go touching on that since the information is there already.

As stated above, I've run into this issue, and my suggestion is to use jQuery Mobile as it was intended and use your own code base to create and store variables using an organized object hierarchy. How you organize it is of your choice, which is precisely what makes javascript such a fantastic language.

We've become too dependent on libraries to solve simple issues that the authors leave to us to solve using our inventive and personal standard driven methods. Happy Coding to all, with an encouragement to build, not just design!

like image 20
Brett Weber Avatar answered Oct 13 '22 21:10

Brett Weber