JSON operation in Android Phonegap - android

I'm trying to send a getJson call from my app (login form) to get an external JSON from PHP file. and there if login and password are ok. My app will redirect from login.html to home.html.
This is my script located in login.html shown below
<script>
function testlogin() {
var login = $('#login').val();
var password = $('#password').val();
$.ajax({
url: "http://http://10.0.2.2/YasmineMarket.php",
data: { login: JSON.stringify(login), password: JSON.stringify(password) },
dataType: "jsonp",
success: function(json, textstatus) {
if (json.d == 'Login Success') {
var url = "acceuil.html";
$(location).attr('href', url);
}
else {
alert("Wrong Username or password");
var url = "index.html";
$(location).attr('href', url);
}
},
error: function(xmlHttpRequest, textStatus, errorThrown) {
if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
return;
else
alert(errorThrown);
}
});
}
</script>
<!DOCTYPE HTML>
<html >
<form id="loginForm" method="GET" >
<table border="0" align="center">
<tr><td></td></tr>
<tr><td align="center"><input type="text" name="login" id="login" /></td></tr>
<br>
<tr><td align="center"><input type="password" name="password" id="password" /></td></tr>
<tr><td align="center"><input type="submit" value="Connexion" onlick="testlogin();" class="button" /></td></tr>
</table>
</form>
</body>

This code is not sufficient to find the actual problem here. But this link might help you to write a server authentication. Please go through my old post about jsonp ajax request to a web server using jquery mobile and phonegap.

Related

Ionic - App works fine on browser and iOS simulator but not in android simulator

I am really new to the mobile development world and trying my hands on it using IonicFramework.
I am creating a login form and on successful login the user gets take to another state which is called viewMyList. Everything seems to be working fine when I run the command ionic serve I am able to login and proceed to the next state and all seems to be fine on iOS simulator as well but on Android simulator on clicking the login button nothing happens, I don't see any error either.
My attempt
login.html
<ion-view title="Login">
<ion-content class="has-header" padding="true">
<form class="list">
<h2 id="login-heading3" style="color:#000000;text-align:center;">Welcome back!</h2>
<div class="spacer" style="width: 300px; height: 32px;"></div>
<ion-list>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" placeholder="" ng-model="credentials.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="text" placeholder="" ng-model="credentials.password">
</label>
</ion-list>
<div class="spacer" style="width: 300px; height: 18px;"></div>
<a class="button button-positive button-block" ng-click="login()">Sign In</a>
</form>
</ion-content>
</ion-view>
ng-click is linked with login()
Here is my loginCtrl which contains the login() function
.controller('loginCtrl', function ($scope, $state, $ionicHistory, User) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
$scope.message = "this is a message loginCtrl";
})
Here is my User service that takes care of the login logic
angular.module('app.user', [])
.factory('User', function ($http) {
var apiUrl = 'http://127.0.0.1:8000/api';
var loggedIn = false;
return {
login: function (credentials) {
console.log(JSON.stringify('inside login function'));
console.log(JSON.stringify(credentials));
return $http.post(apiUrl + '/tokens', credentials)
.success(function (response) {
console.log(JSON.stringify('inside .then of login function'));
var token = response.data.token;
console.log(JSON.stringify(token));
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
persist(token);
})
.error(function (response) {
console.log('inside error of login function');
console.log(JSON.stringify(response));
})
;
},
isLoggedIn: function () {
if (localStorage.getItem("token") != null) {
return loggedIn = true;
}
}
};
function persist(token) {
window.localStorage['token'] = angular.toJson(token);
}
});
Here is the route behind the login
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
I am really clueless at the moment as I cant seem to figure out why nothing happens on Android, from my troubleshooting all I could find was when I click on login button the code does not seem to be going inside the following function.
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
Any help will really be appreciated.
Install whitelist plugin first.
cordova plugin add cordova-plugin-whitelist
add following code in your config.xml file under your root directory of project
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
If still you are facing any issue, then you can check console while you are running in android device using chrome remote debugging
Connect your device with your machine.(Make sure USB debugging should be enable on your mobile).
write chrome://inspect in browser in your desktop chrome.
you will see connected device, select inspect and check console for log.

Phonegap Ajax call returns Internal Server Error

I newbie in Phonegap Android App Development. I am trying to connect my App with remote MS SQL Server Database, I wrote an ASP.Net Web-service also to connect these two.
But when I call this Web-service via JQuery ajax() method it returns "Internal Server Error".
Code :
<html>
<head>
<title>PhoneGap Example</title>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<link rel="stylesheet" href="css/jquery.mobile.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.mobile.js"></script>
<script type="text/javascript" >
function button_clicked(){
var name = $.trim($("#txtName").val());
var contact = $.trim($("#txtContactNumber").val());
var type = $.trim($("#txtType").val());
if(name.length > 0)
{
$.ajax({
type: "POST",
url: "http://my-domain.com/DocNote_WebService/DoctorMaster.asmx/insertDoctor",
data: "{doctorName: "+ name + ",contactNumber: "+ contact + ",doctorType: " + type +"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data) {
alert('Record Saved Sucessfully.....!!!!');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('ERROR: '+thrownError);
}
});
}
}
</script>
</head>
<body>
<section id="page1">
<header><h1>DocNote</h1></header>
<div class="content" data-role="content">
<h3>Enter Doctor Info</h3>
<div data-role="fieldcontain">
<input type="text" data-clear-btn="true" name="txtName" id="txtName" placeholder="Enter Name"/>
<br/>
<input type="text" data-clear-btn="true" name="txtContactNumber" id="txtContactNumber" placeholder="Contact Number"/>
<br/>
<input type="text" data-clear-btn="true" name="txtType" id="txtType" placeholder="Type"/>
<br/>
<button id="btnSubmit" class="ui-btn ui-btn-inline ui-corner-all" onclick="button_clicked()">Submit</button>
<button id="btnCancel" class="ui-btn ui-btn-inline ui-corner-all">Cancel</button>
</div>
</div>
</section>
</body>
</html>
My Web-service Method :
[WebMethod]
public void insertDoctor(String doctorName, String contactNumber, int doctorType) {
using (SqlConnection connection = ConnectionFactory.getConnection())
{
SqlCommand sqlCommand = new SqlCommand("Insert into DOCTOR_MASTER (DOCTOR_NAME, DOCTOR_CONTACT_NUMBER,DOCTOR_TYPE) values (#name,#contact,#type)",connection);
sqlCommand.Parameters.AddWithValue("#name", doctorName);
sqlCommand.Parameters.AddWithValue("#contact",contactNumber);
sqlCommand.Parameters.AddWithValue("#type", doctorType);
sqlCommand.ExecuteNonQuery();
}
}
Tell me what I am doing wrong .....
Thanks in Advance .........
Pass the data as an object, not a string...
$.ajax({
type: "POST",
url: "http://my-domain.com/DocNote_WebService/DoctorMaster.asmx/insertDoctor",
data: {
"doctorName": name,
"contactNumber": contact,
"doctorType": type
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data) {
alert('Record Saved Sucessfully.....!!!!');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('ERROR: '+thrownError);
}
});
Finally, I found Solution Here.
data: "{ firstName: 'Aidy', lastName: 'F' }"
Then, I modified my Code and it Worked.
$.ajax({
type: "POST",
url: "http://my-domain.com/DocNote_WebService/DoctorMaster.asmx/insertDoctor",
data: "{doctorName:'" + doctorName + "', contactNumber:'" + contactNumber + "', doctorType:'" + doctorType + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(response) {
alert('Record Saved Sucessfully.....!!!!');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('ERROR: '+thrownError);
}
});

Cannot submit the data to another page using jquery mobile

<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.2.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="home">
<div data-role="header">
<h1>jQuery Mobile loadPage() Method</h1>
</div>
<div data-role="content" id="content_container">
<form id="my_form">
<input type="text" id="name" />
<input type="text" id="surname"/>
<input type="button" id="yes">
</form>
</div>
</div>
<script>
var storePageLoaded = false;
$(document).on('click', '#yes', function() {
$.ajax({
type: "POST",
url: "searchresult.php",
data: $("form#my_form").serialize(),
success: function(data){
$.each(data, function(i, elem) {
nic_list.push({label: elem['p_nic']});
});
}
}).done(function (data) {
$.mobile.changePage('next-page.html',{transition:"slide"});
}).fail(function (jqXHR, textStatus) {
alert(error);
});
return false;
});
</script>
I created this page to send some form data to php file and print the data in a another page.But when i try this i get following error .I have change the code little bit to retrieve the data .It works fine but i need to populate the data next-page.html
10-14 11:10:05.108: E/Web Console(9066): Uncaught TypeError: Object #<Object> has no method 'jqmData' at http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js:2
$(document).on('click', '#yes', function() {
$.ajax({
type: "POST",
url: "searchresult.php",
data: $("form#my_form").serialize(),
success: function(response){
alert(success);
}
}).done(function (data) {
$.mobile.changePage('next-page.html',{transition:"slide"});
}).fail(function (jqXHR, textStatus) {
alert(error);
});
return false;
});

Phonegap Can't Redirecting to a page

So I have this form where upon submission I do a SQL query and redirect it to another page. But when I try to test this on the android tablet it doesnt redirect, nor does it error meaning the SQL call is valid and works...can someone please help me out
<div class="wrapper">
<div class="oneSection">
<form method="post" action="" id="barcodeForm">
Barcode: <br/>
<input name="barcode" id="barcode" type="text" class="sub"/><br/>
<input type="submit" class="open" id="before" value="SUBMIT" onclick="check()" />
</form>
</div>
</div>
<script type="text/javascript">
function check() {
var barcode = $('#barcode').val();
if(barcode.length <= 0) {
$('#barcode').css('border', '2px solid red');
e.preventDefault();
return;
} else {
alert(barcode.length);
var barcode = $('#barcode').val();
checkBarcode(false, barcode);
}
}
function checkBarcode(doAuto, id) {
var successCall;
if (doAuto) {
successCall = function (tx, result) {
var item = result.rows.item(0);
$('[name="client"]').val(item['cname']);
$('[name="address"]').val(item['address']);
$('[name="sitename"]').val(item['sname']);
$('[name="model"]').val(item['model']);
$('[name="lasttested"]').val(item['ltest']);
$('[name="nounits"]').val(item['units']);
$('[name="comments"]').val(item['comments']);
}
} else {
test.innerHTML += 'at the start<br/>';
successCall = function () {
var URL = 'test.html?id=' + id;
window.location.href = URL;
}
}
var queryDB = function queryDB(tx) {
tx.executeSql(getBarcode, [id], successCall, onError);
}
db.transaction(queryDB, onError);
}
</script>
What happens at the moment is that it submit's the input value and resets the form without forwarding the page or anything...

How to share text message in LinkedIn wall in PhoneGap?

I am developing one application in PhoneGap in that application i want to share text-message in Facebook,twitter and LinkedIn. for ANDROID-LinkedIn i am searching many Google links but i am getting good one. please help me i am struck here
I am implementing this sample:
<html>
<head>
<title>OAuthSimple w/ LinkedIn</title>
<script src="OAuthSimple.js"></script>
<script>
/*
You must edit the two following lines and put in your consumer key and shared secret
*/
var consumer_key = "ibmay1qostgk";
var shared_secret = "4HqeDRZ2ZKAvASlM";
/*
Nothing below here needs to be edited for the demo to operate
*/
var oauth_info = {};
var oauth = OAuthSimple(consumer_key, shared_secret);
function parse_response(response, callback)
{
response.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { oauth_info[$1] = $3; });
callback.call();
}
function authorize_url()
34{
set_url("https://www.linkedin.com/uas/oauth/authenticate?oauth_token=" + oauth_info.oauth_token, document.getElementById("au"));
}
function access_token_url(pin) {
oauth.reset();
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: pin}, signatures: oauth_info}).signed_url;
set_url(url, document.getElementById("at"));
}
function fetch_profile_url() {
oauth.reset();
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/v1/people/~", signatures: oauth_info}).signed_url;
set_url(url, document.getElementById("fp"));
}
function set_url(url, element) {
element.value = url;
var span = document.createElement("span");
span.innerHTML = " <a href='" + url + "' target='_blank'>Open</a>";
element.parentNode.insertBefore(span, element.nextSibling);
}
window.onload = function() {
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {oauth_callback: "oob"}}).signed_url;
set_url(url, document.getElementById("rt"));
}
</script>
</head>
<body>
<h1>OAuthSimple w/ LinkedIn</h1>
<label for="rt">Request Token URL:</label> <input type="text" size="100" name="rt" id="rt" >
<br><br>
<label for="rtr">Request Token Response:</label><br><textarea rows="5" cols="75" name="rtr" id="rtr"></textarea>
<br>
<button onclick="javascript:parse_response(document.getElementById('rtr').value, authorize_url)">Parse Response</button>
<br><br>
<label for="au">Authorize URL:</label> <input type="text" size="100" name="au" id="au">
<br><br>
<label for="vp">Verifier PIN Code:</label> <input type="text" size="100" name="vp" id="vp">
<button onclick="javascript:access_token_url(document.getElementById('vp').value)">Get Access Token URL</button>
<br><br>
<label for="at">Access Token URL:</label> <input type="text" size="100" name="at" id="at">
<br><br>
<label for="atr">Access Token Response:</label><br><textarea rows="5" cols="75" name="atr" id="atr"></textarea>
<br>
<button onclick="javascript:parse_response(document.getElementById('atr').value, fetch_profile_url)">Parse Response</button>
<br><br>
<label for="fp">Fetch Profile URL:</label> <input type="text" size="100" name="fp" id="fp">
</body>
</html>
thanks in advance
Heres a full example of login and sending msg linkedIn using Phonegap
ref = window.open('https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=APIKEY&scope=w_messages r_network r_emailaddress r_fullprofile&state=APISECRET&redirect_uri=SOMEACTIVESITE','_blank','location=no');
ref.addEventListener('loadstart', function(e){
$.mobile.loading( 'show' );
if(e.url.indexOf('?code=') >=0 ){
if(e.url.match(/=[^]+&/)){
var code = e.url.match(/=[^]+&/)[0].substring(1).replace('&','');
window.sessionStorage.setItem('code', code);
ref.close();
$.ajax({
url: 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+code+'&redirect_uri=http://janbeeangeles.com&client_id=jwwwdjplwubu&client_secret=ygMy3EpVcs6IAORE',
success: function(a){
$.ajax({
url : 'https://api.linkedin.com/v1/people/~/mailbox?oauth2_access_token='+a.access_token,
type: 'post',
headers : {
'Content-Type' : 'application/json',
'x-li-format' : 'json'
},
data: JSON.stringify({
"recipients": {
"values": [
{
"person": {
"_path": "/people/~",
}
}]
},
"subject": "asdasdasd on your new position.",
"body": "You are certainly the best person for the job!"
}),
success: function(a){
alert(2222)
},
error: function(a){
alert(JSON.stringify(a))
}
})
},
error: function(a){
alert(JSON.stringify(a))
}
})
}
}
});

Categories

Resources