PDO and ajax call - javascript

I am new to PHP-PDO and need some assistance. My application routes all controllers to the index.php though a routes.php file. For example, when my sign-up form is submitted the form is handled action=index.php?controller=signup&action=createuser. The routes.php computes this creates a new signupcontroller($_POST) object and calls createuser(). Once the user is created a welcome page is required_once, which, with javascript, I build a grid of check-boxes. After the check-boxes are built with jquery onchange that makes a ajax call, or supposed to create an ajax, but does not work.
The url is suppose to send params with it to change the controller and action in order to call an appropriate function, and store the check-box option. However, when I check the box nothing happens.
ajax call:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
var str = $('#interests').serialize();
$.ajax({
type: 'POST',
url: 'index.php?controller=interest&action=set_user_interest',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
});
routes.php
function call($controller, $action){
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'interest':
require_once 'models/interest.php';
$controller = new InterestController();
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array(
'interest'=>['set_user_interest', 'error']
);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('landing', 'error');
}
} else {
call('landing', 'error');
}
index.php
<?php
session_start();
require_once('greenCupOfWater.inc');
if (isset($_GET['controller']) && isset($_GET['action'])) {
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = 'landing';
$action = 'landing_page';
}
require_once 'views/layout.php';
?>
layout.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1">
<title>Witit</title>
<link rel="icon" type="image/png" sizes="32x32" href="../images/icons/favicon-32x32.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Work+Sans:100" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="stylesheets/master.css">
<link rel="stylesheet" href="stylesheets/welcome.css">
<link rel="stylesheet" href='stylesheets/<?php echo $controller ?>.css'>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<?php include 'routes.php'; ?>
<script src="scripts/main.js" charset="utf-8"></script>
<script src="scripts/modalHelper.js" charset="utf-8"></script>
</body>
</html>
javascript files:
function build_interest(it, src){
var intrst = it;
var htag = it+"-header";
//var chng = 'this.form.submit()';
var ctr = document.createElement('div');
ctr.setAttribute('class', 'interest_container');
var lbl = document.createElement('label');
lbl.setAttribute('for', intrst);
var img = document.createElement('img');
img.setAttribute('src', src);
var title = document.createElement('h2');
title.setAttribute('id', htag);
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', intrst);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', intrst);
inp.setAttribute('name', intrst);
inp.setAttribute('value', 1);
lbl.appendChild(img);
ctr.appendChild(lbl);
ctr.appendChild(inp_f);
ctr.appendChild(inp);
ctr.appendChild(title);
var elem = document.getElementById('interests');
elem.appendChild(ctr);
document.getElementById(htag).innerHTML = it;
}
function myFunc(obj) {
var num = 0;
for (var src in obj) {
if ((obj.hasOwnProperty(src))&&(obj[num].Interests_Pix!==null)) {
build_interest(obj[num].Interests, obj[num].Interests_Pix);
}
++num;
}
}

Related

Request to server with $.ajax doesn't return success - PHP

I'm trying to make a request to server on a with jQuery and ajax and process the request with PHP , however , every time the server responds with '404' (in console: Error occurred!) code that I specified in the PHP file.
The problem is that even with the correct username and password , still the request wouldn't return as code 200 (successful).
HTML file is named login.php , JS file is named main-2.js and the file that process the request is login-process.php This is my HTML code :
$(document).ready(() => {
$('#awesome-login-form').submit((event) => {
event.preventDefault();
const data = $('#awesome-login-form').serialize();
const adminUserName = $('#login-user-name').val();
const adminPassword = $('#login-password').val();
$('#usr-err-msg').html('');
$('#psw-err-msg').html('');
$('#total-err-msg').html('');
$.ajax({
type: "POST",
url: "login-process.php",
dataType: "json",
data: data,
success: (data) => {
if (data.code === '200') {
console.log('It works!');
window.location.href = 'dashboard-index.php';
} else if (data.code === '404') {
console.log('Error occurred!');
$('#usr-err-msg').innerText = data.nameErrMsg;
$('#psw-err-msg').innerText = data.passwordErrMsg;
$('#total-err-msg').innerText = data.totalError;
}
}
});
});
});
<!doctype html>
<html lang="en">
<head>
<title>IPConcrete | Admin-Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="css/login-custom-style.css">
<link rel="stylesheet" type="text/css" href="vendor/my-grid.css">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto&display=swap">
<link rel="stylesheet" type="text/css" href="css/my-style.css">
</head>
<body>
<h2 style="text-align:center;color:#ff5e15;margin-top:50px;">IPCONCRETE</h2>
<div class="log-form">
<h2 style="color:#ff5e15;font-weight:800;">Login to your account</h2>
<form method="post" action="login.php" id="awesome-login-form">
<input type="text" name="admin_name" title="username" placeholder="username" id="login-user-name" />
<p id="usr-err-msg" style="display:inline-block;"></p>
<input type="password" name="admin_password" title="username" placeholder="password" id="login-password" />
<p id="psw-err-msg" style="display:inline-block;"></p>
<button type="submit" name="login_btn" class="btn" id="login-submit">Login</button>
<p id="total-err-msg" style="display:inline-block;"></p>
<a class="forgot" href="#">Forgot Username?</a>
</form>
</div>
<!--end log form -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/main-2.js"></script>
</body>
</html>
and the PHP file code is:
<?php
require_once('functions.php');
require_once('config.php');
$nameErrMsg = '';
$passwordErrMsg = '';
$totalError = '';
$_SESSION['isAdmin'] = false;
$adminName = $_POST['admin_name'];
$adminPassword = $_POST['admin_password'];
$errorStatus = false;
if (checkEmpty($adminName)) {
$errorStatus = true;
$nameErrMsg = 'The user name field is empty!';
}
if (checkEmpty($adminPassword)) {
$errorStatus = true;
$passwordErrMsg = 'The password field is empty!';
}
if (!(checkEmpty($adminName)) && !(checkEmpty($adminPassword))) {
$sqlCommand = "SELECT FROM `io9mp_admins` WHERE `user_name` = ? AND `password` = ?";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$sqlCommandPrepare->execute([
$adminName,
$adminPassword
]);
//Checking if the user input values are equal to the data base fields...
$result = $sqlCommandPrepare->fetch();
if (mysqli_num_rows($result) === 1) {
$errorStatus = false;
} else if (mysqli_num_rows($result) !== 1) {
$errorStatus = true;
}
}
if ($errorStatus === true) {
echo json_encode([
'code' => '404', 'totalError' => $totalError, 'nameErrMsg' => $nameErrMsg, 'passwordErrMsg' => $passwordErrMsg
], JSON_THROW_ON_ERROR, 512);
}
else if ($errorStatus === false) {
echo json_encode([
'code' => '200',
], JSON_THROW_ON_ERROR, 512);
}
the checkEmpty() funtion is in functions.php:
<?php
function checkEmpty($input){
return empty( trim($input) );
}
You can't use mysqli_XXX functions when you're using PDO. Change:
if (mysqli_num_rows($result) === 1) {
$errorStatus = false;
} else if (mysqli_num_rows($result) !== 1) {
$errorStatus = true;
}
to
$errorStatus = !$result;

JS, how can i refresh the page or div when json data changed?

Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);

Ajax call does not work properly and refreshing table data with ajax call

I am currently developing a web app. What i need, first of all, is when my html page loads, to invoke an ajax call to my servlet, which will search a database and return as response all the entries of a table as an html table. Whatever i have tried this does not seem to work, although i am using a ready function in which i do the ajax call.
Secondly when my html table is created, a verify button is added to unverified entries. What i need is when i press the verify button to call my servlet, update my database and then refresh my html table.
adminPage (servlet)
public class AdminPage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String result = "";
System.out.print("in get");
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "Sk1994!!");
PreparedStatement ps = con.prepareStatement("select * from user");
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int accepted = 0;
result = "<table class='table table-striped'><thead><tr>";
for (int i = 1; i <= numberOfColumns; i++) {
String name = rsmd.getColumnLabel(i);
System.out.println("h sthlh legetai: |" + name + "|");
if (name.equals("accepted"))
accepted = i;
result += "<th>" + name + "</th>";
}
System.out.println("column is: " + accepted);
result += "<th>Verification</th></tr></thead><tbody>";
while (rs.next()) {
boolean verified = true;
result += "<tr>";
for (int i = 1; i <= numberOfColumns; i++) {
result += "<td>" + rs.getString(i) + "</td>";
if (accepted == i)
if (rs.getString(i).equals("0"))
verified = false;
}
if (verified)
result += "<td></td></tr>";
else
result += "<td><button onclick='runPop(this);'>Validate</button></td></tr>";
}
result += "</tbody></table>";
con.close();
} catch (Exception e) {
e.printStackTrace();
}
out.println(result);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.print("in post");
String uname = request.getParameter("uname");
System.out.println("Arxise");
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "Sk1994!!");
PreparedStatement ps = con.prepareStatement("update user set accepted=? where username=?");
String newValue ="1";
ps.setString(1, newValue);
ps.setString(2, uname);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using bootstrap and angular in my html page, i have removed most the included things
Js and ajax calls
function myFunction() {
$.ajax({
type: 'GET',
url: '../adminPage',
success: function(data) {
$("#result").html(data);
}
});
}
$(document).ready(function() {
myFunction();
});
function runPop(el) {
var report = el.parentNode.parentNode.cells[1].innerHTML;
$.ajax({
type: 'POST',
url: '../adminPage',
data: {
"uname": report
},
success: function(data) {
$.ajax({
type: 'GET',
url: '../adminPage',
success: function(data) {
$("#result").html(data);
}
});
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Tempting EveryDay</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">-->
<link href="../css/jquery.datetimepicker.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
<!-- Theme CSS -->
<link href="../css/agency.min.css" rel="stylesheet">
<link href="../css/mycss.css" rel="stylesheet">
<link href="../css/agency.css" rel="stylesheet">
</head>
<body>
<div id="result"></div>
<button type="submit" onclick="myFunction();">press me</button>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Contact Form JavaScript -->
<script src="../js/jqBootstrapValidation.js"></script>
<script src="../js/contact_me.js"></script>
<!-- Theme JavaScript -->
<script src="../js/agency.min.js"></script>
<!-- Angular js -->
<script type="text/javascript" src="../js/angular.min.js"></script>
<script type="text/javascript" src="../js/app.js"></script>
</body>
</html>
The output i want is this:
wanted output
i ve managed to show it by adding a button to do the ajax call manually, but even then, when i press the validate button, ajax post is not done and servlet is not called.
Also even if i update the database manually, when i refresh the page the html table does not update.
I am asking too much but every single clue could help me a lot. Thanks

How to send form data with window.open() using InAppBrowser

I have a requirement that i need to send form data with window.open(). am going to integrate PayU money to Ionic and AngularJS application at that scenario i need to send some form data from window.ope() using InAppBrowser Cordova plugin but am not able to send form data.
following code written in my app.js
var example = angular.module('starter', ['ionic', 'ngSanitize']);
example.run(function($ionicPlatform, $timeout) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
});
example.controller("ExampleController", ['$scope', '$interval', function($scope, $interval) {
$scope.myHTML = 'Check out my programming blog while you are here';
$scope.testmethod = function() {
onDeviceReadyEWEWE();
}
}]);
// Global InAppBrowser reference
var iabRef = null;
function iabLoadStart(event) {
var winName = 'MyWindow';
//var winURL='https://test.payu.in/_payment.php';
var winURL = 'https://test.payu.in/_payment';
// var winURL='https://test.payu.in/merchant/postservice.php?form=2';
var windowoption = 'resizable=yes,height=600,width=800,location=0,menubar=0,scrollbars=1';
//var params = { 'param1' : '1','param2' :'2'};
var params = {
'key': 'gtKFFx',
'txnid': 'mdd0sss9023',
'amount': '100',
'productinfo': 'oxygenconcentrator',
'firstname': 'test',
'email': 'test#gmail.com',
'phone': '9000024100',
'surl': 'https://payu.herokuapp.com/success',
/* 'Furl' :'https://www.payumoney.com/mobileapp/payumoney/failure.php', */
'Furl': 'https://payu.herokuapp.com/failure',
'Hash': '9feaefa45b5b68c7091f7f1ff513183f3fca5b23b47d47d760c285c8ad2d5f9fd1ec9514f2bad5d3672b6cb9138af5dd5350a5cf1e87c6f20ca26817ee02ae77'
};
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", winURL);
form.setAttribute("target", winName);
for (var i in params) {
if (params.hasOwnProperty(i)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = i;
input.value = params[i];
form.appendChild(input);
}
}
document.body.appendChild(form);
// window.open('', winName,windowoption);
form.target = winName;
console.log(form.action);
form.submit();
alert(event.type + ' - ' + event.url);
}
function iabLoadStop(event) {
alert(event.type + ' - ' + event.url);
}
function iabLoadError(event) {
alert(event.type + ' - ' + event.message);
}
function iabClose(event) {
alert(event.type);
iabRef.removeEventListener('loadstart', iabLoadStart);
iabRef.removeEventListener('loadstop', iabLoadStop);
iabRef.removeEventListener('loaderror', iabLoadError);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
function onDeviceReadyEWEWE() {
//form.submit();
var options = {
location: 'yes',
clearcache: 'yes',
toolbar: 'yes',
closebuttoncaption: 'DONE?'
};
iabRef = window.open('https://test.payu.in/_payment', '_blank', options);
iabRef.addEventListener('loadstart', iabLoadStart);
iabRef.addEventListener('loadstop', iabLoadStop);
iabRef.addEventListener('loaderror', iabLoadError);
iabRef.addEventListener('exit', iabClose);
}
and in my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController">
Testing
<p ng-bind-html="myHTML"></p>
<button ng-click="testmethod()">button</button>
</ion-content>
</ion-pane>
</body>
</html>
so please help me out how to send form data with URL in window.open();
After Edit:
finally Integrated Inappbrowser to My Ionic app and cracked a solution.please find the URL for PayU Money Integration for Hybrid appsPayUmoneyIntegartion

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

Categories