load my facebook username and picture in HTML Page - android

I m developing and android application using phonegap . I m follwing this tutorial https://github.com/phonegap-build/FacebookConnect/tree/962eb0a1c07935ff813e28aa9eaa5581f2e10416 and i m succesfully connecting to facebook in Phonegap and i m displaying my Facebook username and Picture in my (Index.html) and sending my informations to the server.
In this page (index.html) , i have a button that let me go to another HTML Page(Profile.html). I m trying to display my facebook informations to this page (Profile.html) as well as the (Index.html)
Here is the code in my JS File that let me display my informations after a connect to facebook in my Indx.HTML Page and let me also send these informations to the server:
function handleStatusChange(session)
{
console.log('Got the user\'s session: ' + JSON.stringify(session));
alert('Got the user\'s session: ' + JSON.stringify(session));
if (session.authResponse)
{
//document.body.className = 'connected';
//Fetch user's id, name, and picture
FB.api('/me',
{
fields: 'name, picture,first_name,last_name,email'
},
function(response)
{
if (!response.error)
{
document.body.className = 'connected';
user = response;
console.log('Got the user\'s name and picture: ' + JSON.stringify(response));
console.log('FB name, ' + response.name);
console.log(('FB picture, ' + response.picture.data.url));
// alert('Fb Id,'+response.id);
//alert('Email'+response.email);
// alert('FB Last name'+response.first_name);
// alert('FB name, ' + response.last_name);
//Update display of user name and picture
if (document.getElementById('user-name'))
{
document.getElementById('user-name').innerHTML = user.name;
}
if (document.getElementById('user-picture'))
{
document.getElementById('user-picture').src = user.picture.data.url;
}
var callDataLogin = JSON.stringify({'serviceName':"global_functions", 'methodName':'login',"parameters":[response.id,response.last_name,response.first_name,response.email]});
$.post('Server URL', callDataLogin, function(resp){}).done(function(data)
{
console.log(data);
//alert(data);
//alert(" Send User Facebook info to server , Login");
});
}
else
{
document.body.className = 'not_connected';
console.log('Error getting user info: ' + JSON.stringify(response.error));
if (response.error.error_subcode && response.error.error_subcode == "458")
{
setTimeout(function()
{
alert("The app was removed. Please log in again.");
}, 0);
}
logout();
}
clearAction();
});
}
else {
document.body.className = 'not_connected';
clearAction();
}
}
And here is the code in my Index.html page that let me display my Facebook User Informations:
<div id="page-root" class="page">
<div class="show_when_connected">
<div id="welcome"><img id="user-picture" /><br /><span id="user-name"></span></div>
</div>
I also add this code to my Profile.html Page to display my facebook User Informations
<div id="page-root" class="page">
<div class="show_when_connected">
<div id="welcome"><img id="user-picture" /><br /><span id="user-name"></span></div>
</div>
But it s not displaying anything in my Profile.html as in my Index.html
Thanks for your help
////////////////////////////////////////UPDATE/////////////////////////////////////////////
in my js file here is the code that i put
<script>
//get the id
var getFbId=sessionStorage.getItem('Fbid');
//set the id html
document.getElementById('idget').innerHTML =getFbId;
var getFbName=sessionStorage.getItem('FBName');
//set the Name html
document.getElementById('Nameget').innerHTML =getFbName;
var getFbPicture=sessionStorage.getItem('FBPicture');
//set the Picture html
document.getElementById('Pictureget').innerHTML =getFbPicture;
</script>
and in my Profile.html here is the code that i used:
<div id="idget"></div>
<div id="Nameget"></div>
<img id="Pictureget">

You just set your fb credentials in localstorage/session storage after this you can retrieve in any page that you want.
function(response)
{
if (!response.error)
{
document.body.className = 'connected';
user = response;
console.log('Got the user\'s name and picture: ' + JSON.stringify(response));
console.log('FB name, ' + response.name);
console.log(('FB picture, ' + response.picture.data.url));
//set the id in session storage/localstorage
sessionStorage.setItem('Fbid',response.id);
//For localstorage
window.localStorage.setItem( 'Fbid', response.id);
}
}
For get this value in another html page by this way
//get the id from session
var getFbId=sessionStorage.getItem('Fbid');
//get the id from localstorage
var fromLocalStorage=window.localStorage.getItem( 'Fbid' );
//set the id html
document.getElementById('idget').innerHTML =getFbid;

Related

Citrus Payment Redirect Url not working

I am integrating citrus payment into android app , everything is working well in sandbox till my transaction is successful but once my transaction is successful i get below logs :
MOTO SUCCESSFUL***{"txMsg":"Transaction successful","pgRespCode":"0","redirectUrl":"https://sandbox.citruspay.com/mpiServlet/715259413249776a736d6a62546c5a413247745871773d3d"}
Which says transaction is successful and i can see in my sandbox consumer account that transaction is successful but when it redirect to above url in log it shows below screen :
And When i try to press back button :
There is no way out to reach my last activity in application i tried to put return url in app as : private static final String RETURN_URL = "http://my.app";
which should return to my activity but didn't help, Any help or hint would be greatly appreciated.
I resolved the Issue Via sending the return page url which was hosted on my server itself like below :
<?php
$access_key = "xxxx"; //put your own access_key - found in admin panel
$secret_key = "xxxxx"; //put your own secret_key - found in admin panel
$return_url = "http://xxxxx/Citrus/return_page.php"; //put your own return_url.php here.
$txn_id = time() . rand(10000,99999);
$value = $_GET["amount"]; //Charge amount is in INR by default
$data_string = "merchantAccessKey=" . $access_key
. "&transactionId=" . $txn_id
. "&amount=" . $value;
$signature = hash_hmac('sha1', $data_string, $secret_key);
$amount = array('value' => $value, 'currency' => 'INR');
$bill = array('merchantTxnId' => $txn_id,
'amount' => $amount,
'requestSignature' => $signature,
'merchantAccessKey' => $access_key,
'returnUrl' => $return_url); echo json_encode($bill); ?>
And return url shows the message successful transaction and back to Activity ! .
<html>
<head>
<script type="text/javascript">
var globaldata;
function setdata(data) {
globaldata = data;
}
function postResponseiOS() {
return globaldata;
}
function postResponse(data) {
CitrusResponse.pgResponse(data); }
</script>
</head>
<body>
</body>
</html>
<?php
$secret_key = "xxxxx";
$data =array();
foreach ($_POST as $name => $value) {
$data[$name] = $value;
}
$verification_data = $data['TxId']
. $data['TxStatus']
. $data['amount']
. $data['pgTxnNo']
. $data['issuerRefNo']
. $data['authIdCode']
. $data['firstName']
. $data['lastName']
. $data['pgRespCode']
. $data['addressZip'];
$signature = hash_hmac('sha1', $verification_data, $secret_key);
if ($signature == $data['signature'])
{
$json_object = json_encode($data);
echo "<script>
postResponse('$json_object');
</script>";
echo"<script> setdata ('$json_object');
</script>";
}
else {
$response_data = array("Error" => "Transaction Failed",
"Reason" => "Signature Verification Failed");
$json_object = json_encode($response_data);
echo "
<script>
postResponse('$json_object');
</script>";
echo"
<script>
setdata ('$json_object');
</script>";
}
?>

Login with Twitter on phonegap app

I'm trying to implement the login action using the twitter acount in my cordova app.
I have found a script using Childbrowser.js file to do it but it's not supported anymore so that I am trying to do it using the inappBrowser plugin instead of the childbrowser.
I succeeded in opening the login interface but after the login it redirect me to a web page. How can I redirect to my html local page? can I get ignore the redirect url and just get the access token?
this is the code that I am using:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
return ('here test');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){alert('stop: ' + loc.url);
// Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
alert('ok entred');
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://127.0.0.1:81/?") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
Actually there is error in your code you have to fix it:
the https://api.twitter.com/1/account/verify_credentials.json?skip_status=true' is no more used change it to 1.1.
also change the way you close your inappbrowser.
this code works for me try it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
retiurn ('hhhh');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text,'_blank', 'location=no'); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){//alert('stop: ' + loc.url);
Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
// alert(loc.url);
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.url.indexOf("http://127.0.0.1:81/?") >-1) {
// Parse the returned URL
var index, verifier = '';
var params = loc.url.substr(loc.url.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
// alert(verifier)
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
// alert('key'+twitterKey);
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
cb.close();
},
function(data) {
// alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1.1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>

What's the best way to ensure privacy during communication between Cordova based mobile app and web server?

I've built a mobile app based on Cordova, for both iOS and Android, i need to make secure communication between app and server. Request to server, in javascript, are like this:
request.open("GET", 'http://url/service?firstElement='+elem+'&secondElement='+elem2, false);
I've tried to use RSA encryption generating public and private key locally using pidCrypt libraries, the 2048bits key requires too long time to be generates, so i've used 512bits.
The server is not be able to decrypt the message.
I'm looking for a better solution.
Try Using Send Ajax Request, Like This. I assume that you use php for Dynamic code (Server Side).
Here is Sample of HTML file which presant on your cordova, phonegap directory.
<form method = "post" action = "#!">
<div class="col-md-4">
<span class="help-block">Name</span><input type="text" name="username" class="form-control" />
</div>
<br>
<div class="col-md-4">
<span class="help-block">Password</span><input type="text" name="password" class="form-control" />
</div>
<input type = "submit" value = "Save" class = "btn btn-success right" onClick="UpdateRecord();"/>
</form>
<script>
function UpdateRecord()
{
var name = $("[name='username']").val();
var host = $("[name='password']").val();
jQuery.ajax({
type: "POST",
url: "php/login.php",
/* Or */
/*url: "https://www.yoursite.com/page",*/
data: "username="+ username+"& password="+ password,
dataType: "html",
cache: false,
success: function(response){
if(response == 'true') {
$.session.set("myVar", username);
window.location.href='profile.html';
}
else {
$("#errorMessage").html("Invalid Entry, Please Try Again");
}
}
});
}
</script>
And PHP File for Handle Query.
Please Not that code is not tested and it may change as per your need. You can perform any encryption method and use any function here.
<?php
include 'config.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(!empty($username) && !empty($password))
{
//$result = mysql_query("SELECT * FROM ".$db.".users WHERE username='$username' and password ='$password'");
$result=mysql_query("select * from ".$db.".users WHERE email = '$username' ");
while($data = mysql_fetch_row($result))
{
$original_password = $data[3];
$salt = $data[4];
$hashedPass = sha1($salt.$password);
$fullusername = $data[16]." ".$data[17]; // Used Only for create full name session
if ($original_password == $hashedPass)
{
$_SESSION['username'] = $fullusername;
$_SESSION['useremail'] = $username;
$_SESSION['UserID'] = $data[0];
echo 'true';
}
}
}
?>
Edit
request.open("GET", 'http://url/service?firstElement='+elem+'&secondElement='+elem2, false);
Avoid to use GET method while sending sensitive data.
Edit, Helpful Link
Local storage protection in phonegap application

Calling an External Javascript Function

I have an app i'm programming in Javascript/JQuery. I'm using PhoneGap and want to use localStorage to store the users credentials the first time they open the app and then autofill next time the user opens the app. I want to call the checkPreAuth() right when the page loads. But It's not calling my function. Can anybody help me?
Calling the function from login.html:
<script>
$(document).ready(function() {
checkPreAuth();
});
</script>
And the function in my digest_auth.js:
function checkPreAuth() {
var form = $("#loginForm");
var values = new Array();
var username = $('#username').val();
var password = $('#password').val();
if(window.localStorage["username"] == undefined && window.localStorage["password"] == undefined) {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
alert('Saved username and password');
} else {
alert(username + ', ' + password);
}
}
Maybe this is the answer to your problem. I faced this problem and instead of using document ready of jquery, i used this:
JQuery document.ready vs Phonegap deviceready

JQuery Mobile ListView

I'm having 2 strange problems with the code I'm using to pull in some data to use in a listview. Here is my javascript:
function getOrders(status, url) {
$(function () {
//check if url from pagination
if (!url) {
url = api_url + '/orders/?callback=?&status=' + status;
} else {
url = root_url + url + '&callback=?';
}
$.mobile.loading('show');
$.getJSON(url, null, function (d) {
//declare a variable with which to build our output (it's best to buffer output and only do one append at the end since DOM manipulation is CPU expensive)
var output = '';
//iterate through the data (we could also get rid of the jQuery here by using `for (key in data) {
$.each(d.objects, function (index, value) {
output += '<li><a id="' + value.reference + '" href="view_order.html" class="view_order"><h3>' + value.reference + ' - ' + value.client.company + '</h3><p>' + value.order_date + ' ' + value.user.username + '</p></a></li>';
});
$('#orders_list').html(output).listview('refresh');
//if paginated, update next button
if (d.meta.next) {
$("#id_ordersNext").attr('href', d.meta.next);
$("#id_ordersNext").show();
} else {
$("#id_ordersNext").hide();
}
if (d.meta.previous) {
$("#id_ordersPrevious").attr('href', d.meta.previous);
$("#id_ordersPrevious").show();
} else {
$("#id_ordersPrevious").hide();
}
$("#id_ordersTotal").html(d.meta.total_count);
$.mobile.loading('hide');
});
});
}
$(function () {
//bind the nav
$(".order_nav").die();
$(".order_nav").live('click', function () {
$(".order_nav").each(function () {
$(this).removeClass('ui-btn-active');
});
$(this).addClass('ui-btn-active');
getOrders($(this).attr('href'));
return false;
});
//bind the view order
$(".view_order").die();
$(".view_order").live('click', function () {
//save var
window.viewOrderReference = $(this).attr('id');
$.mobile.changePage("view_order.html");
});
$("#id_ordersNext,#id_ordersPrevious").die();
$("#id_ordersNext,#id_ordersPrevious").live('click', function () {
getOrders(null, $(this).attr('href'));
return false;
});
//default view
getOrders('Order Placed');
});
Here is the html I'm using for the page that's being loaded via JQMobile:
<div data-role="page" data-needs-auth='true'>
<script src="js/list_orders.js"></script>
<div class="headerDiv" data-role='header' data-theme='b'>Home
<h1>Jubilee Distributors</h1>
Login</div>
<div data-role='navbar'>
<ul>
<li>Placed</li>
<li>Picked</li>
<li>Delivered</li>
</ul>
</div>
<div data-role="content">
<ul data-role='listview' id="orders_list" data-filter="true"><li>No records found</li></ul>
<p>Previous <span id='id_ordersTotal' class='record-count'></span> records found Previous
</p>
</div>
<div id='footerDiv' data-role="footer"></div>
</div>
This all works fine in any browser on a desktop, but when I run it on an Android device 2 things happen, or rather don't.
The last line in the $(function() - getOrders('Order Placed'), doesn't seem to execute, or if it does, it's not updating the list with the returned result. If I click the first link with the "Orders Placed" it works no probs.
The addClass is not actually adding the class.
Like I said, this all works fine in any desktop browser, but not on the Android device.
Any ideas?
EDIT: Fixed the second problem, however the first problem still exists.. It works if I navigate to the page, then away from it, then back again tho.
Fixed this error by changing the dom ready function to pageinit.

Categories

Resources