Unable to post to Restful API through Ajax using android phone - android

I am developing Android application using PhoneGap. I am trying to execute simple login module, it works fine in web browser. But when it comes to apk, its not working. It is not able to post request to Restful API.
var usr = $('#email_address').val();
var pass = $('#password').val();
if(usr != '' && pass != ''){
alert("Before Calling Method");
$.ajax({
url:APIURL +"api/sample/sample123",
type: "POST",
crossDomain : true,
data: {username:usr,password:pass},
dataType: "json",
success: function(data){ /*Here I am posting some dummy code, I can't show original code*/
var response = eval(data);
alert(response.response);
}
});
When I am executing this on android phone, I am getting only first alert above i.e "Before Calling Method" but it is not showing another alert. I have configured res/xml/cordova.xml as
<access uri="*" subdomains="true"/>
Also I have referred some previous related doubts from StackOverflow. But It didn't helped me. Please help me to, I am waiting for positive response...

try this one
formData = {
username: $('#email_address').val(),
password: $('#password').val()
}
$.ajax({
url: APIURL + "api/sample/sample123",
type: "POST",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
alert(data);
}
});

Related

Ajax request not sending on android cordova

Ajax request not sending on android studio with cordova. I tried a simple request to google but it does not work either.
What i already tried :
- Change minSdk to 23
- Add cordova whitelist plugin and permissions for https and http in config.xml
- add android:usesCleartextTraffic="true" in AndroidManifest
- i have nothing in my network profiler but ajax return a timeout error
- Outside my app, my request work
Code
$.ajax({
type: "POST",
url: OAUTH2_URL,
cache : false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth($("#login").val(), $("#pwd").val()));
},
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: json,
timeout: 5000,
success: function (data) {
etape3(data);
},
error: function (xhr, ajaxOptions, thrownError){
SpinnerPlugin.activityStop();
navigator.notification.confirm(
'login or password incorrect.', // message
null, // callback
'Error', // title
['Ok'] // buttonName
);
}
})
I don't know what else to do
Thanks !

Ajax basic authentication using Cordova prompting for credentials

I am building a mobile app using Cordova and Cloudant. For this I need to make a POST request using ajax. I am using basic authentication with headers useCredentials=true as required by Cloudant. However this gives me 401 on android device. When emulating on browser it gives me a login screen.
Below is my ajax request.
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
accept: "application/json",
xhrFields: {
withCredentials: true,
},
authorization: base64basicAuthString,
crossOrigin: true,
url: http-url,
data: jsonQuery,
success: function(data) {
//process data
},
error: function(jqXHR, status, error) {
console.log("Error getting data. " + jqXHR.status + " " + error);
}
});

phonegap android ajax over ssl failes

I develope an App with Phonegap and Jquery Mobile. For some reasons I also need to get data from https domains. On IOS everything works perfect, but on Android I always get the following errors and the requests fails
06-17 17:16:33.890 6079-6154/de.sistecs.einlass E/chromium_net: external/chromium/net/socket/ssl_client_socket_openssl.cc:905:
[0617/171633:ERROR:ssl_client_socket_openssl.cc(905)] handshake failed; returned -1, SSL error code 1, net_error -107
Here is a simple sample code
$(document).on("pageinit", function (event, ui) {
$("#test").click(function () {
$.ajax({
type: "POST",
url: "https://test.sistecs.de/sismedia/test.php",
success: function (response) {
$("#testmsg").text(response);
}
});
});
});
I´ve read hundreds of posts, but didn´t find a solution to my problem.
The certificate of the server https://test.sistecs.de/sismedia/test.php is valide.
Can someone help me?
It seems like a Cross Origin problem.
With jQuery Mobile you should set $.mobile.allowCrossDomainPages and $.support.cors to true
<script>
$( document ).on( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
Also be sure that your PHP page sets the headers accordingly. For example:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
header('Access-Control-Allow-Headers: Content-Type');
echo "test";
?>
Edit: I didn't test the code, it is an example. Adapt as you need to.
var myJson = {
'Par1': 'par'
};
$.ajax({
url: baseUrlAjaxServices + "/....",
data: JSON.stringify(myJson),
method: "POST",
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
})
.done(function (data) {
//...
}).fail(function (error) {
console.log(error);
});

Connect database in phonegap

I have created the User interface in phonegap for android. And now I want to insert data in my web based application which is made using php and mysql. So whenever I click on submit button then the information should be stored on the web database of my web application.
How can I achieve this...?
You also can store your information using session storage and ajax.
formData = {
username: $("#username").val(),
password: $("#password").val()
}
$.ajax({
url: "https://example.com/login.php",
type: "GET",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
sessionStorage.setItem("userId", data.user[0].userId);
},
error: function() {
alert("error");
}
});

How do I use PhoneGap to call a webservice

I'm trying to develop an application on phonegap on Android.
What I'm trying to do is call a webservice from my application, this will be used for data access.
I found many sheets online on how to do this, and the simplest one I could find that seems straight forward goes like this
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://www.webservicex.net/stockquote.asmx/GetQuote",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
});
However, All I can see is the text I had already put into the div, the div contents do not change. I'm testing on a Galaxy SIII device directly, not on a simulator.
My guess is that nothing seems to happen because you are getting a fail, not a success. try adding an error handler and see what happens.
.fail(function() { alert("error"); })
You are likely having 'cross domain' issues (because you are trying to get ajax from a different domain) and may need to use JSONP instead of JSON for your dataType. For more info about JSONP, see this post or the docs
EDIT:
Here is a fiddle of this code in action.
$(document).ready(function() {
//here is one way using the 'error' handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error:function(jqXHR, textStatus) {
alert("error:" + textStatus);
},
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
//here is another way using the 'fail' request handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
}).fail(function(jqXHR, textStatus) {
alert( "fail: " + textStatus );
});
});​

Categories

Resources