Jquery Mobile: Sending Data from One Page to the Another

jQuery Mobile: Sending data from one page to the another

One HTML / multiple pages template

Here's an example of passing an attribute from listview to the second page in 1 html multi page template:

http://jsfiddle.net/Gajotres/Gv7UW/ - js object as a storage container

http://jsfiddle.net/Gajotres/J9NTr/ - localStorage as a storage container

Basically what you want to do is create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

    var storeObject = {
firstname : '',
lastname : ''
}

Multiple HTML pages template

Unfortunately this example can't be done through jsFiddle so I will post needed files:

HTML 1 :

<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="operations.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
<a href="#second" class="ui-btn-right">Next</a>
</div>

<div data-role="content">
<ul data-role="listview" data-theme="a" id="test-listview">
<li><a href="page2.html?id=1">Link 1</a></li>
<li><a href="page2.html?id=2">Link 2</a></li>
<li><a href="page2.html?id=3">Link 3</a></li>
<li><a href="page2.html?id=4">Link 4</a></li>
<li><a href="page2.html?id=5">Link 5</a></li>
</ul>
</div>

<div data-theme="a" data-role="footer" data-position="fixed">

</div>
</div>
</body>
</html>

HTML 2 :

<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>
Second Page
</h3>
<a href="#index" class="ui-btn-left">Back</a>
</div>

<div data-role="content">

</div>

<div data-theme="a" data-role="footer" data-position="fixed">

</div>
</div>
</body>
</html>

operations.js :

$(document).on('pageshow', '#second', function(){   
alert(getParameterByName("id"));
});


function getParameterByName(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

User authentication demo

Another example that can't be shown with a jsFiddle example, unlike previous one, this one will have attached SQL script. I would advise you to create a better db reading logic, this one is a simple solution, prone to SQL injection, but it will work well for your assignment:

index.php :

<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/custom.js"></script>
</head>
<body>
<div data-role="page" id="login">
<div data-theme="a" data-role="header">
<h3>Login Page</h3>
</div>

<div data-role="content">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
<a data-role="button" id="login-button" data-theme="b">Login</a>
</div>

<div data-theme="a" data-role="footer" data-position="fixed">

</div>
</div>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3></h3>
</div>

<div data-role="content">
Here goes content
</div>

<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>

json.php :

<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object

$username = $jsonObject->{'username'}; // Get username from object
$password = $jsonObject->{'password'}; // Get password from object

mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
@mysql_select_db("test") or die( "Unable to select database"); // Connect to database called test

$query = "SELECT * FROM users WHERE user_name = '".$username."' and user_pass = '".$password."'";
$result=mysql_query($query);
$num = mysql_numrows($result);

if($num != 0) {
echo "true";
} else {
echo "false";
}
?>

custom.js :

$(document).on('pagebeforeshow', '#login', function(){ 
$('#login-button').on('click', function(){
if($('#username').val().length > 0 && $('#password').val().length > 0){
userObject.username = $('#username').val(); // Put username into the object
userObject.password = $('#password').val(); // Put password into the object
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'login', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});

$(document).on('pagebeforeshow', '#index', function(){
if(userObject.username.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#login", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="header"] h3').append('Wellcome ' + userObject.username); // Change header with wellcome msg
//$("#index").trigger('pagecreate');
});

// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/JSONP_Tutorial/json.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Login unsuccessful, please try again!'); // In case result is false throw an error
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
}
}

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
username : "",
password : ""
}

localhost.sql :

-- phpMyAdmin SQL Dump
-- version 3.4.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 02, 2013 at 11:58 AM
-- Server version: 5.5.20
-- PHP Version: 5.3.10

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test`
--
CREATE DATABASE `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `test`;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) NOT NULL,
`user_pass` varchar(64) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`user_id`, `user_name`, `user_pass`) VALUES
(1, 'gajotres', 'testpass');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

More info

If you want to learn more about this topic take a look at this article. You will find several solutions with examples.

Pass parameter between pages using jquery mobile

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});

[Example][3]:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});

$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->

</body>
</html>

second.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">

</div> <!--content-->
</div><!--page-->

</body>
</html>

Solution 2:

Or you can create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
firstname : '',
lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$('#index').live('pagebeforeshow', function (e, data) {
alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

More info

If you want to learn more about this topic take a look at this article. You will find several solutions with examples.

pass parameters between two pages in two different files in JQuery Mobile

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});

[Example][3]:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});

$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->

</body>
</html>

second.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">

</div> <!--content-->
</div><!--page-->

</body>
</html>

Solution 2:

Or you can create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
firstname : '',
lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$('#index').live('pagebeforeshow', function (e, data) {
alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

More about this can be found in my blog article.

jQuery Mobile: Get data passed to page via changePage

Solution

Send them like this:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?parameter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$("#index").live('pagebeforeshow', function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});

More examples can be found here: jQuery Mobile: document ready vs page events, just look for chapter: Data/Parameters manipulation between page transitions.

Example:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});

$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->

</body>
</html>

second.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">

</div> <!--content-->
</div><!--page-->

</body>
</html>

More info

If you want to learn more about this topic take a look at this article. You will find several solutions with examples.

Passing data between pages with jQuery Mobile?

One thing that I think is cool about JQM is that you don't have to use parameters to pass data between pages. Since you're in the same DOM as the first page, you can access data using plain old variables, i.e.

field1 = $('[name=field1]').val();
field2 = $('[name=field2]').val();

And so long as you're using the ajax feature of JQM you could do the following in the next page:

$('.title').text(field1);

I made a jsfiddle example for you.

Other ways would be to use the localStorage or sessionStorage api or there are also some plugins mentioned in the docs.

  1. page params
  2. JQM router plugin

jquery mobile send data to internal page and read from there

If it is an internal page I assume, that you are using single .js file. If so, there is no need in passing data. Just make a global variable (outside any functions) and store there your values.

OR

Have you considered caching your list page?

OR

Have you tried local storage? Here are some examples of using:

localStorage.removeItem("item");
localStorage.setItem("item", yourdata);
localStorage.getItem("item");
localStorage.clear();

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

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();
});
}
});


Related Topics



Leave a reply



Submit