Sending the below request in my phonegapp-ed android app works for GET but not POST.
With GET, everything works. With POST, the request goes through but the POST variables
are not coming through on the server side, and the server returns a
json response that says 'no parameters supplied.'
POST works fine from our mobile app - it is just the phonegap app where we are having an issue. What am i missing here??? Thanks in advance for any help you can provide!
I've tried changing the settings on the $.ajax call, the android manifest, everything I can think of.
Also, i'm using Android 2.2 and Phonegap 1.0
function goTeam(){
var dataString={lat:currentLocation.lat(),lng:currentLocation.lng()}; // this all works
$.ajax({
url: 'http://example.com/request/goTeam',
data: dataString,
dataType: 'json',
success:
function(b) {
if(b.status==1){ // woo hoo! it works
} else {
// the request went through but something was wrong - this is what i'm getting with POST
}
},
type: 'post', // works with GET, doesn't work with POST
error: function(jqXHR, textStatus, errorThrown){ alert("Noooo."); }
});
Are you trying cross-domain requests? Only GET requests work this way. You can use JSONP for this kind of request, but only GET works.
Phonegap does work with both GET and POST - cross-domain security issues do not apply. We had an idiosyncratic error our code that was preventing it from working. Phonegap is pretty awesome!
Related
I get "Http failure response for https://www.google.com: 0 Unknown Error" when I request from Secured url.
I am trying to test my ionic/angular mobile app. When I tried with http requests I had problem with Android 9, but with Android 7 was working fine. Anyhow I need to set my backend to public https server. So now I'm testing with https request and none of 7 and 9 Android versions works.
I am using Angular 7 ,
"#ionic/angular": "^4.6.1",
"#ionic-native/core": "^5.0.0",
"rxjs": "~6.5.1"
I made these small functions in order to make my problem simpler.
inside my html file i have this code:
myFile.html
<ion-button
(click)="onStartTest()"
>Click me</ion-button>
<p id="testme"></p>
myFile.page.ts
onStartTest() {
this.taskService.onTest().subscribe(result => {
document.getElementById('testme').innerText = 'result ' + result;
console.log(result);
}, error => {
document.getElementById('testme').innerText = error.message;
console.log('Problem ', error.message);
});
}
myTask.service.ts
onTest() {
return this.http.get('https://www.google.com').pipe(
catchError(err => {
return throwError(err);
})
);
}
At first I tried my server's URL but I changed it to "https://www.google.com" just to verify that the backend is correct.
Also I have an interceptors.ts file that I am using it for authentication, but I am not logged in when I execute the onStartTest() function, but im gonna share it anw.
interceptors.ts
import {Injectable} from '#angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('auth_token');
let newHeaders = req.headers;
if (token) {
console.log(token);
newHeaders = newHeaders.set('Authorization', 'Token ' + token);
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
} else {
newHeaders = newHeaders.set('Content-Type', 'application/json');
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
}
}
}
I think these are the necessary files to share for this problem.
I also tested the url of google with Postman just to be sure that I should get a status 200
I am also aware that there is an "add_header" directive (nginx) that adds 'Allow-access-control-origin' when the response code is 20x or 30x. According to my screenshot with Postman, google is responding with 200 status, but my app still gets status 0 error.
Ignore the first Error. It's a function I use with http when the app begins. Right now im testing https.
I tried superficially to use ionic-native library HTTP but my app totally crashed.
I also execute the command ionic serve --ssl but still nothing.
I read somewhere that for secured connection I need a certificate, but I understood that this is a server's work.
I tried to request from Dark Sky from Vanilla JavaScript and it works fine. So there is something wrong with angular/ionic side and not server's.
What am I missing? I really need to fix this problem soon!
I want to send a secured request to an https url and get the appropriate response.
Your main problem is that you are trying make an API to an unsecure call (http) location (http://192....../mobile/tasks) from a secure origin (https://localhost:8100).
This is clearly indicated in your error message and this is not allowed, and has been answered before
Your second problem is that, for testing purposes, you are trying to call a 3rd party https ressource from your website. This only works if the 3rd party ressource implement CORS, which is not the case for Google and api.darksky.net. Sending a GET request with Postman is useless, as Postman will not check for CORS headers before displaying the response. If you want to use Postman to check CORS, send an OPTIONS request to these ressources and you'll see that there are no CORS headers
So the answer is in MDN - CORS
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from, unless the response from other origins
includes the right CORS headers.
This means the back-end I was using needed some more configuration since I was using 'same-origin' policy script. I thought we had it because when we tried from the browser's console to fetch the request it was working fine, but on mobile it wasn't. We had a custom CORS configuration but we changed it to the django-cors-headers. Since we switched to django-cors-headers I could get correctly the response from HTTP and HTTPs requests.
The other answer and comments were really useful to focus to the right direction.
I'm building an app that gets data from a server using basic user authentication. This works fine on Android, but on iOS nothing happens. In safari it also works fine.
This is the code I'm using:
$.ajax({
url: main_url+'api-cache/'+slug+'.json?r='+random_number(),
dataType: 'json',
headers: {
'Authorization': "Basic " + btoa(localStorage.getItem('email') + ":" + localStorage.getItem('password'))
}
})
.done(function(result) {
main_url is a link to an https website.
I have als tried username and passwork like the jQuery documentation says and also beforesend, nothing seems to work. Without the authentication it works fine by the way. Also the result seems to be ".done" because no error is fired in ".fail".
Help? Oh and btw, I'm using Phonegap Build.
Problem solved using a couple of headers on the server instead of changing the app: https://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/
I have api in ajax format ,how can i code in android to get access to server.I have API ID and API key and URL for access to server.
My api code is in the format
$.ajax({
url: 'https://www.abc.com/server/api/user.login'
dataType: 'json',
method: 'POST',
data: {
api_id: 4,
api_key: '06875425-b293-43af-9966-1245125f6bb95b1f7c5e-f932-4916-87f5-db0b298f2',
token: 'api_token_from_previous_call',
},
success: function(response){
console.log(response);
}
});
The code you are showing is jQuery. Are you running that code from within a webview in your Android app or something?
Here are some quick thoughts:
If you need to hit your API from native Android code, I recommend Google's Volley library for making the network request. You can read about Volley here, and this video from last year's Google I/O is a good intro to what it can do.
Once you get the response, you can use the Android JSONObject class to work with it.
EDIT: Solution for JQuery Mobile + Phonegap AJAX Problems:
subdomains="true" property in config.xml is not working in phonegap 2.9.0, every request to a subdomain will return 200 but $.ajax won't fire the success function (and $.getJSON won't fire anyways).
Also: Syntax *.domain.tld as stated in the official doc is not working, only way I found to solve that problem: Setting access origin and acces uri to "*" (all)
<access origin="*"/>
<access uri="*"/>
I'm working on a mobile application using the jQuery Mobile Framework and Phonegap.
I've just added an AJAX request to my application which is used to get data from my webserver.
The page is correctly loading but Android (4.1.2) never fires the AJAX event or never gets a request from the Webserver, in fact it's just hanging on the loading spinner.
Strange thing about this is, that I already use an AJAX request to the same server (but with different domain) that works perfectly fine:
$.getJSON("[...]checkupdate.php?callback=?", function(data){
[...]
})
I've tried to do the second request with $.getJSON too and it worked on my computer but failed on Android. I started looking around for a solution and found out, that setting the cache to false in $.ajax might help so I rewrote my code but it's still not working.
$.ajax({
cache : false,
type: 'GET',
url: requestURL,
dataType: 'jsonp',
context: document.body,
success: function(data){
[...]
}});
Is there anything else to do to get this to work?
I found a way to solve that problem. I noticed, that the subdomains="true" property in phonegap's config.xml is not working. (Phonegap 2.9.0). Every request to a subdomain will return status 200 but $.ajax won't fire the success function (and $.getJSON won't fire anyways). The syntax *.domain.tld as stated in the official doc isn't working for me either, only way I found to solve that problem was setting access origin and acces uri to "*" (all)
I have developed a sample app on Android using Phonegap.
When clicked on a button, an Ajax request is made to the server (http://192.168.0.199:8080/test.php).
The test.php just echoes hello world.
I am using Jquery 1.5 for making the Ajax call.
Here is the code for the Ajax call:
$.ajax({
url:"http://192.168.0.199:8080/test.php",
beforeSend: function(x) {
alert("The URL "+url);
},
type:'POST',
crossDomain: true,
success:function(data) {
alert(data);
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
}
});
But, every time this function is called, it throws an error:
Error Type: No Transport
Error Message: undefined
Error Status: error
Note: I have added the INTERNET Permission in the Manifest file. I am using a G1 device running Android 1.6
Thanks in advance
Looks like you are trying to make an call to a client within a local network.
Try validating you have access to that local network.
As of jQuery 1.5 a new AJAX / XHR implementation is in use. And Android 1.5 / 1.6 doesn't say it supports CORS (crossdomain calling). So a way to 'fix' that is to inform jQuery it does support cors:
jQuery.support.cors = true;
I couldn't reproduce the problem on 2.1 and up. So I expect the XHR implementation from that version on does say it does support cors.