Phonegap - ajax request doesn't work - android

Have tried for hours to create an simple rss reader with phonegap but it doesn't seems to work. Have tried to set access to: <access origin="*"/> but that does not work.
Here is the code I use to get the rss feed:
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent("http://array.se/feed/"),
dataType: 'json',
success: function(data) {
console.log(data.responseData.feed);
$.each(data.responseData.feed.entries, function(key, value){
var thehtml = '<li>'+value.title+'</li>';
$("#factsfeed").append(thehtml);
});
}
});
The code works in the browser but when I try it out on my Android it does not.

Try setting the dataType to 'jsonp'
Also, "document.location.protocol" might not work as the protocol in PhoneGap is file://, you can probably just remove that and append http to the string after it.

Related

Local web service call in Cordova fails with result ERR_FILE_NOT_FOUND

I am using ASP.Net and building an android app using Cordova 5.1.1. I have created the web service (services.asmx) which has a method appStatus and I am calling the same in index.html page. This works perfectly when I run or publish in my laptop. But once I build and run, I get the file not found error with status 0.
Ajax Call
var request = $.ajax({
url: "services.asmx/appStatus",
method: "POST",
data: {},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: ajaxSigninSuccess,
error: ajaxSigninError
});
function ajaxSigninSuccess(response) {
alert(response.d);
}
function ajaxSigninError(response) {
alert(response.status + " " + response.statusText);
}
Following is the response text
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: null
ontimeout: null
readyState: 4
response: ""
responseText: ""
responseType: ""
responseURL: ""
responseXML: null
status: 0
statusText: ""
timeout: 0
Error
GET file:///android_asset/www/services.asmx/appStatus net::ERR_FILE_NOT_FOUND
Please help, thanks in advance.
You have problem about server + client side.
I call server is where your service ASP.Net ("services.asmx") deploy.
Client is your mobile app in device.
1. When your server + client in your computer.
Ex: url service: "http://localhost:8080/services.asmx" then when you call ajax by url 'services.asmx/appStatus' then it will get path of html file(include ajax code) and prepend to url. If html file is "http://localhost:8080/index.html" then url call by ajax will be: "http://localhost:8080/services.asmx/appStatus". I think it working with you.
2. When server deploy in you computer and client running in device (emulator).
Ip address of your computer and emulator in your computer is different.
Your app start with index.html file: "file:///android_asset/www/index.html" and so that url call by ajax will be: "file:///android_asset/www/services.asmx/appStatus" not found any service or file at url.
3. Solutions: call ajax by full url: "http://domain.com/services.asmx/appStatus" or if your server deploy in local then "http://ipaddress:port/services.asmx/appStatus".

ajax xhr.getResponseHeader("user header") is not working for Android native browser

I am trying to make an AJAX call to a servlet. In the servlet I am setting headers. But the header is not displayed back from the response in the Android native browser. I am not able to read the header. In other browsers it is working fine.
javascript code:
$.ajax({
type: 'GET',
url: url,
cache : false,
async: false,
success: function(data, status, xhr) {
code = xhr.getResponseHeader('X-code');
}
});
I am taking care or CORS issues.
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Request-Method", "*");
response.addHeader("Access-Control-Allow-Headers", "X-code");
response.addHeader("Access-Control-Expose-Headers", "X-code");
Things are working fine for other mobile/web browser, but not working for Android native browser.
Need assistance.
Thanks in advance.

Integrating ajax, jquery based webservices with android

I am trying to consume a webservice currently made in ajax. I have no idea what this web service is actually doing other than it uses POST Data. When i try to see its output on POSTMAN (Rest api client) I am getting errors.
This is the structure of web service :
var request = {};
request.UserName = "some data"; // this should be always hard coded like this
request.Password = "some data"; // this should be always hard coded like this
request.CurrentUsername = "admin"; // this is hard coded like this for now
request.FirstName = "some data";
request.LastName = "some data";
var send = {};
send.request = request;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "some link",
data: JSON.stringify(send),
dataType: "json",
async: false,
success: function (msg) {
// Process the result here
},
error: function () {
//alert("error");
// Display the error here in the front end
}
});
});
});
I need to get its output in android. Since i have little knowledge in ajax, jquery(backend) and done json parsing(in android) with post method using web service link and parameters. Please guide me how to implement in this case.
Moreover i usually check web service output on postman but here it is giving me bad request every time.
Please help.
have you tried using Fiddler4 by Telerik? i was struggling for 2 weeks at work doing something very similiar to this. I was using webclient to send data from Android to my web page. I got errors non stop. nothing online helped. using fiddler i was able to see what my post data was and where it was and all details. it should help you narrow down a lot of things.
Yes finally got a way to move it. It is very simple and following header is needed in android end thats all
httpPost.setHeader("Content-Type", "application/json");

upload image file from jquery to node.js

I am trying to upload a file from andriod application, using Jquery to node.js using express..
My client side code is:
function uploadData(win) {
var padI = imagedata.length-1
while( '=' == imagedata[padI] ) {
padI--
}
var padding = imagedata.length - padI - 1
var user = load('user')
$.ajax({
url:'http://'+server+'/lifestream/api/user/'+user.username+'/upload',
type:'POST',
contentType: false,
processdata:false,
data:imagedata,
success:win,
error:function(err){
showalert('Upload','Could not upload picture.')
},
})
}
I have used post form without any content type because if i use multipart/form-data it says error about boundary ..
my server side code using node.js is:
function upload(req,res) {
var picid=uuid()
console.log('Got here..' + __dirname)
//console.log('Image file is here ' + req.files.file.path)
// console.log('local name: ' + req.files.file.name)
var serverPath = __dirname+'/images/' + picid+'.jpg'
fs.rename(
req.files.file.path,
serverPath,
function(error) {
if (error) {
console.log('Error '+error)
res.contentType('text/plain')
res.send(JSON.stringify({error: 'Something went wrong saving to server'}))
return;
}
// delete the /tmp/xxxxxxxxx file created during download
fs.unlink(req.files.file.path, function() { })
res.send(picid)
}
)
}
when the file comes to server, it gives an error of res.files.file is undefined ..
I have searched alot of forums, they say that res.files.file is only access when contenttype is multipart/form-data but then the boundary problem occurs
Any help on that is highly appreciated
Boundary is a special sequence of characters that separates your binary data.
You should submit MIME type as multipart/form-data, as well as set your imagedata to FormData() type (from your snippet it's not clear if it is FormData type).
Here are similar issues and solutions:
How to set a boundary on a multipart/form-data request while using jquery ajax FormData() with multiple files
jQuery AJAX 'multipart/form-data' Not Sending Data?
A great alternative to writing this code is to use filepicker.io This allows you to connect to yoru own s3 bucket. When the file is saved, you get back a callback with the S3 url, you can then simply pass that url to your node api, and save it. I have used this to avoid having to write extra server code for handling file uploads. Extra bonus, if you need to do this with images, and want users to be able to edit the images, you can use Aviary which allows an image to be edited locally, and you then get back another s3 url, that you can then save to your server..

Using PhoneGap, can't load local .html file using Ajax on Android only

I'm using PhoneGap (latest), Jquery 1.7. I'm having troubles getting some html loaded via AJAX into a div. My problem is simple, I have an index.html file in the www/ directory. And a js file that does this:
$.ajax({
type:"GET",
timeout:10000,
dataType: "html",
async: false,
cache: false,
url: "file:///android_asset/www/_liqui-cult.html",
success: function(data) {
$('#data_details .description').html(data); // never runs
},
error: function(xhr,msg){
alert(xhr.status + ", " + msg);
if(xhr.status == 0 || xhr.status == "0"){
alert(xhr.responseText); // always blank, if runs
}
}
});
Having spent the day Googling this error, I've tried numerous things, but the AJAX call never succeeds. I've tried changing the url to simply, _liqui-cult.html (without the file:// -based url). I've also tried /_liqui-cult.html.
I started out trying with the JQuery $.load, and that wasn't working, so I switched to the more verbose $.ajax call.
No matter what I do, I either get a 404 as the status, or, if I change the url to http://_liqui-cult.html, I get a status of 0, but nothing in the responseText.
So, I took JQuery out of the equation, and tried a simple XMLHttpRequest, as so:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && (xmlhttp.status==200 || xmlhttp.status==0))
{
$('#data_details .description').html(xmlhttp.responseText);
$.mobile.changePage('#screen_detail');
}
}
xmlhttp.open("GET","_liqui-cult.html", true);
xmlhttp.send(null);
Again, I've tried every conceivable url pattern to map to the html file. And still, the best I can get is xmlhttp.responseText is blank.
So how about cross-origin issues? Here is what I've tried:
<access origin=".*"/>
<access origin="file://*"/>
<access origin="*"/>
Again, I've tried all ways of mapping to the html file, with those different access origin settings, and I still cannot load the html file.
Any ideas?
Changing the name of the html file that gets AJAX-loaded from "_liqui-cult.html" to the same name without the underscore "liqui-cult.html" fixed the problem.
Seems something else is wrong in your project. The following gist have some of the files from my test application and it works without any issue in Android.
https://gist.github.com/2873186

Categories

Resources