Passing data between pages in JQuery Mobile

I am working on a JQuery Mobile application which is based on single page template design. In this design, there is one main page in the application and all other pages are loaded by JQuery using AJAX and content is embedded into the DOM of the main page.

I have a couple of pages in the application and I switch between pages using changePage. One of the issues I struggled a bit initially was, how to pass data between pages? The signature of changePage is

$.mobile.changePage(to,options)

‘to’ argument is URL of the page to which you want to change to. ‘options’ is an object with many different keys. One of the keys is ‘data’ and the documentation says – “data (object or string, default: undefined) The data to send with an Ajax page request.”.

So I could pass data to the page I want to change to either by passing URL parameters directly, or as ‘data’ in ‘options’ in changePage i.e.

$.mobile.changePage("newPage.html?param1=value1");

OR

$.mobile.changePage("newPage.html", {data:{param1:'value1'}});

I thought passing values in ‘data’ in ‘options’ is cleaner solution. But the problem is that JQuery Mobile does not help you to retrieve ‘data’ in the new page. I was hoping that any of the page event callback functions of JQuery Mobile, like pageload, pagechange etc., would pass ‘data’ that was passed from invoking page as one of the arguments. But it does not.

BTW, changePage function also appends parameter passed as ‘data’ to the page URL, so in that sense above two options are the same. So you will have to handle retrieving data yourself. I thought either JQuery or JQuery Mobile would have convenience functions to retrieve URL parameter, but surprisingly they don’t have. However there is a JQuery plug-in which does this – JQuery URL Parser . To use this plug-in, include jquery.url.js after you include jquery file –

<script src="jquery-1.7.2.js"></script>
<script src="jquery.mobile-1.1.0.js"></script>
<script src="jquery.url.js"></script>

Then you can retrieve URL params as follows –

<div data-role="page" id="newPageId">
    <script type="text/javascript">
        $("#newPageId").on("pageshow", onPageShow);

        function onPageShow(e,data)
        {
            var url = $.url(document.location);

            var param1 = url.param("param1");
        }
    </script>
</div>

When passing data values, JQuery Mobile replaces spaces (in values) with ‘+’, so you will have to replace them when you get param values. Or you can use encodeURIComponent and decodeURIComponent e.g.

in the page where you are calling changePage –

$.mobile.changePage("newPage.html",{data:{param1:encodeURIComponent('value with spaces')}});

And in the page where you want to retrieve param values –

var url = $.url(document.location);

var param1 = url.param("param1");
if (param1 != undefined)
    param1 = decodeURIComponent(param1);

-Ram Kulkarni

Update :
I was asked to provide a complete example for the scenario I discussed in this post. So I have posted a demo here.

This entry was posted in JQuery Mobile and tagged , , . Bookmark the permalink.

39 Responses to Passing data between pages in JQuery Mobile

  1. grindiador says:

    do you have a fb fanpage

  2. eric says:

    Why the hell do you need to pass data between pages when you keep thé js context ?

  3. mapo says:

    thanks :) easy and clear solution !

  4. I’ll take a guess at what Eric means. I think he’s referring to keeping settings in a global context object so when the page changes, the data persists. The difficult part about this approach is that when all you need is to pass simple keys/parameters between pages it’s just easier to put those keys in URLs as parameters. This saves you from having to write an on click event handler for those links to save that data to a context object. This would however not be a good approach if you are going to put more than just a parameter into the URL because browsers have their own URL character limits that will bite you, so on that count, Eric’s advice should probably be taken.

    • Ram Kulkarni says:

      Yes, I had guessed that Eric meant global scope, but just wanted to be sure …

      I do agree with you that URL params are good when data size is small and global scope is good when data size is large.

  5. Heads up to everyone using parameters in URLs. Once a user goes to something like /index.html?param=foo and then they try to go to index.html?param=bar they will always end up at /index.html?param=foo. The patch from flodev is currently working for me against the 1.1.1 tag.

    See https://github.com/jquery/jquery-mobile/issues/2859

  6. atul says:

    thanks for the toutorial

  7. Oscar says:

    Thanks my friend, I was so tired and disappointed finding it, but you give me the light

  8. Holy says:

    Thanks For the post. I was sooooo bored to find out passing data between html pages in phonegap android apps. I didn’t try it. bt may be this is the solution.

  9. WP Coder says:

    Good presentation, You give is very helpful and I thank you very much..

  10. Neha Thakkar says:

    02-01 15:43:51.282: E/Web Console(1172): TypeError: Result of expression ‘$.mobile’ [undefined] is not an object. at file:///android_asset/www/index.html:13

  11. john says:

    Ram Kulkarni

    Do you have source code for us to download?

  12. cris says:

    Hello Ram,

    I hope you can send us or me a complete running source code to test. And that will be a big help. Just zip it.

  13. Ram Kulkarni says:

    I have posted a complete demo here.

  14. Andrew Christopher says:

    Why dont you have html, body etc tags on page2? when you add these in it doesn’t work?

    • Ram Kulkarni says:

      Because JQM fetches the second page using AJAX and it embeds only that code from the second page (in the DOM) which is in the top div page (i.e. <div data-role=”page”>). Everything outside this div is not executed when JQM loads the second page.

  15. Hachem says:

    how to send values to a php file located ine a server??and dow to recuper them..please i nned a form exemple with php mysql jquery mobile

  16. Mike says:

    Ram, I can’t get this to work. I’ve created a new page div (data-role=”page”) in my main page. If I don’t include the js files in that page then I get a “$ undefined” error at runtime. But if I include the js files then all controls on my page are duplicated. Any thoughts on what my issue is?
    Thanks!

    • Ram Kulkarni says:

      Are you trying the same example I posted and it is not working? From your comment it appears that you have both the pages in the main file. If you post the complete source code then I might be able to help.

    • Tal says:

      There is a problem leaving html snippet in this thread.

      Just consider the fact that you had href with parameters and on the navigated to page you handled the pageinit event.

  17. vaishali says:

    Thanx for this clear explanation of this topic… :)

  18. Muthu says:

    But when i put the second page script into inside head its not working….why?

  19. Akachai says:

    The second page should not content html or header or body tag, because JQM is not execute any code outside the top of first div tag when loading the second page

  20. Gabe says:

    I tried your example but each time that I click the Back button it stays on the same page. I need to click it twice for it to go back to Page1.

    • Gabe says:

      I was using Chrome but it works great in Firefox. However, I just copy/paste your code into two web pages of mine and I can see the parameter in the url but it doesn’t show it on the web page.

  21. Neel says:

    wonderful brother :) I have got the solution which I am finding for 3 days… thanks you very very much…

  22. muniraja says:

    hello sir, i want to code for google login using phonegap

  23. muniraja says:

    dear sir i need session in phonegap to initiate, how to initiate session in phonegap

  24. suresh says:

    hello ram,
    am suresh ,,,i am developing app in which i need to get the mobile contacts in my phone ..
    i sucessfuly got the contacts in to my page and i put checkboxes too…
    now i need to select some of them and display in another page …cud u pls help me ….only jquery

    • Ram Kulkarni says:

      If your application is a single page app, where you load the main page and subsequent pages are fetched (using XHR) and loaded into the main page then I would suggest you use a global variable to hold selected contact objects. This is how JQueryMobile single page application works. I would not pass selected contacts as URL parameter in this case.
      If you application is not a single page app, then consider using some kind of persistent storage e.g. localstorage or (browser) database.

      • suresh says:

        hi am unale to sort out …am pasting my code here..pls go thru ..

        ContactsApp

        //document.addEventListener(“deviceready”, onDeviceReady, false);
        //function onDeviceReady() {
        // $(“#ContactList”).html(”);
        //};
        function onBodyLoad() {

        if (navigator.userAgent.match((“#ContactList”).html(”))

        ) {
        onDeviceReady();
        } else if (typeof navigator.device == “undefined”) {
        document.on(“deviceready”, onDeviceReady, false);
        } else {
        onDeviceReady();
        }
        }
        function GetContact() {
        $(“#ContactList”).html(”);
        var options = new ContactFindOptions();
        options.filter = “”;
        options.multiple = true;
        var fields = [“name”];
        navigator.contacts.find(fields, onSuccess, onError, options);
        };

        function onSuccess(contacts) {
        for (var i = 0; i < contacts.length; i++) {
        var id = "id"
        var name = '';
        if (contacts[i].name != null) {
        name = contacts[i].name.formatted;
        };
        //name = 'name' + i;
        $("#ContactList").append('’);
        $(“#ContactList”).append( ” + name + ”);
        // $(“#ContactList”).append(” + name + ‘ ‘ + i + ”);
        //}
        //console.log(contacts[i]);
        }
        };
        function onError(contactError) {
        alert(‘onError!’);
        };

        //var isSelectedShown = false;
        //$(document).ready(function () {
        // isSelectedShown = false;
        showSelectedItems();
        selectedData = new Array();
        var selectedData = new Array();
        function isSelected(cb, i) {
        if (cb.checked == true) {
        selectedData.push($(“#cb” + i));
        }
        else {
        selectedData.pop(i);
        }
        }

        function showSelectedItems() {
        if (isSelectedShown == false) {
        $(“#ContactList”).empty();
        for (var i = 0; i < selectedData; i++) {
        $("#ContactList").append('’);
        $(“#ContactList”).append(selectedData[i].val() + ”);
        }

        isSelectedShown = true;
        }
        else {
        isSelectedShown = false;
        showItems();
        }
        }

        function showSelectedItems1() {
        //alert(selectedData.length);
        if (selectedData.length > 0) {
        if (!window.localStorage) alert(“Sorry, you’re using an ancient browser”);
        else {
        localStorage.selectedItems = JSON.stringify(selectedData);
        }
        //sessionStorage.setItem(“selectedItems”, JSON.stringify(selectedData));
        $(location).attr(“href”, “Selectedlist.html”);
        }
        else {
        alert(“Please select atleast one item”);

        }

        }

        body {
        font-size:16px;
        }
        button {
        padding: 20px;
        font-size:26px;
        }

        <!– selected –>

        contacts

        Home Back

        am using visual studio 12 web express…
        i need to get contacts of a mobile in to my app ..
        then set check boxes ..
        selected checkboxes values need to display in tht page alone of another page after click button on header

  25. Raheel says:

    Hi ,
    I want to pass data in the form of array to other page.but I could not fix it. My code and HTML is is under:

    Welcome!!!

    Welcome to my blog and you are reading how to write your first jQuery mobile app.

    Image 1

    Image 2

    Image 3

    Image 4

    Image 5

    jQuery By Example

    Page 2

    Index page

    Hooray for page 2!

    <!–
    Apache Cordova

    Connecting to Device
    Device is Ready

    –>

    app.initialize();
    $(document).on(‘pageinit’ , ‘#index’ , function(){
    $(‘#send’).click(function(){
    var test = [];
    $(‘#form input[type=”text”]’).each(function(){
    test.push($(this).val());
    });
    $.mobile.changePage(‘#page2′);
    });
    });

    $(document).on(‘pageinit’ , ‘#page2′ , function(){
    var id = 0;
    for(var i = 0; i < test.length; i++){
    $('#image1').attr('src', test);
    id++;
    }
    });

  26. Cameron Askew says:

    I created a plugin which allows URL parameters and maintains them in the URL so that page refreshes & going directly to a page works. You can find that plugin here:

    https://github.com/CameronAskew/jquery.mobile.paramsHandler

Leave a Reply