Ajax requests to local server with phonegap - ruby-on-rails

I have trouble making ajax requests to a local Rails server using Phonegap. I have a universal whitelist in config.xml for outgoing urls as so:
<access origin="*"/>
and I have the android app with Phonegap set to load the signin page on the rails app like so:
super.loadUrl("http://10.0.2.2:3000/signin")
and I have no problem accessing any of the pages served by the local rails server. However I cannot get ajax requests to go through, the Rails server logs never show a request being received. An example ajax request:
$(document).ready(function() {
if (localStorage.getItem("auth_token") != null) {
$.ajax({
type: 'POST',
url: 'http://10.0.2.2:3000/api/v2/api_login.json',
data: {"token": localStorage.getItem("auth_token")},
success: function (data) {
alert("token saved");
window.location = data.url
}
});
}
else
{
alert("no token");
}
});
I have also tried setting the url domain in the ajax request to both 127.0.0.1:3000 and www.lvh.me:3000 with no luck.
If I access the pages through a browser and not Phonegap everything works fine. If I push the code to heroku and access the url to point to heroku everything works fine. The problem seems to be submitting ajax requests to the local server.

Related

RequestVerificationToken cookie is not being sent in Ajax POST requests

Here is the Ajax code:
var token = $('form input[name="__RequestVerificationToken"]').val();
var data = {};
data.Type = $(e.target).attr('type');
data.__RequestVerificationToken = token;
url = '#Url.Action("MyAction", "MyController")';
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: "html",
success: function (result) {
//do some stuff
},
error: function (err) {
//display error
}
})
In IE 11 Developer tools, during the initial load of the page (GET), I can see that the RequestVerificationToken cookie is being set. Also, the form element for RequestVerificationToken is being populated too. During the Ajax POST, however, the cookie is not part of the request.
Chrome works fine in both places, and during the Ajax POST, the cookie is present. IE 11 works locally (localhost), but this problem arises when IE 11 accesses the application on the server, and this error is returned:
The required anti-forgery cookie "__RequestVerificationToken_L1JldkNvbm5lY3Q1" is not present.
For some reason IE 11 doesn't include the cookie in the Ajax POST when the application is on the server. I can see that it is missing in the Network tab of IE Developer Tools. In the Network tab of Chrome Developer tools, the cookie is present, and the POSt works.
ASP.NET MVC 5

Jquery AJAX from remote host

Hi I am trying to get json from a remote host using this piece of code Example at fiddle,
Here i want to add that i am using jquery cross domain ajax plugin
$("button").click(function() {
jQuery.ajax({
url: "http://50.116.19.49/rest/user.json",
type: 'GET',
success: function(result) {
$("div").html(result.responseText);
}
});
});​
I am using jquery AJAX GET method. The problem is when i try to use POST instead of GET it stops working, Need help.!
Thanks
It's possible to limit request by method on server side.
So that doesn't mean If it works with GET than that also must work with POST. As I see your web service doesn't allow origin access for POST method.
Here is an example how it's allowed for different type of request in PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET")
header("Access-Control-Allow-Origin: *");
echo "lan";
else {
echo "disabled";
}
?>

Phonegap App communicate with Rails 3 App using authentication

I am trying to write an iOS app using Phonegap to communicate with my Rails3 app. I cannot figure out how to handle authentication. I am using Devise/Warden in my Rails app.
I am able to login successfully in my iOS app via ajax but then subsequent calls are giving me a "Unauthorized". It appears that the session cookie isn't getting set in my iOS app.
How do I keep my iOS app aware of my rails authenticated session?
The answer was two fold.
First I had to add this to my ajax requests in the iOS app:
xhrFields: {
withCredentials: true
}
as in...
$.ajax({
url: ....,
type: "GET",
xhrFields: {
withCredentials: true
},
complete: hideLoader,
error: function(xhr,txt,err) {
// you can't get back anyways
window.location.hash = "";
},
success: function(data,status,res) {
window.location.hash = "";
}
});
Second I had to add this to my Application Controller in the Rails app:
def protect_against_forgery?
unless request.format.json?
super
end
end

Jquery ajax request on IOS using Phonegap - Ajax not working

I have a simple html login form, deployed on Xcode using phonegap framework.
When the submitLogin button is clicked, I then sent the login credentials using ajax request to verify the login.
This is my javascript function to handle the login:
function submitLoginForm (login_id, login_pass){
//here we need to communicate with the php files in the server
console.log ("debug 1 ");
$.ajax({
type: "POST",
url: "http://192.168.1.9/serverapp/loginHandler.php",
data: "login_id=" + login_id + "&login_password=" + login_pass,
success: function(loginStatus){
navigator.notification.alert ("login request successfully sent");
console.log ("debug 2");
if (loginStatus == "success"){
console.log ("debug 3 ");
location.href = "main.html";
}
else{
console.log ("debug 4 ");
location.href="index.html?errcode=1";
}
}
});
console.log ("debug 5 ");
}
After submitting the login form, I could see that the console only printed "debug 1" message. What could be wrong in this case? If the ajax request fails, it is still supposed to print the "debug 5" message, but it did not print anything and just skip the whole thing, except the first debug message.
I could access the php url from my browser, so I am sure that the problem is not with the php code. I have been trying to spend several hours with no result. Do you have any similar problem with Phonegap IOS framework, and how did you fix it?
Problem solved.
I was using an external jquery file from http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
And it appeared that the external jquery url is blocked by the ios simulator, so I have to put that url in the whitelist.
Steps:
In your XCode phonegap project, browse into Resources folder.
Go to Supporting Files directory, and edit the PhoneGap.plist file.
In the External Host list, add any external URLs that you want to
access (including the external jquery url, and any other url that you
would use in your ajax request).
I hope this will be useful for other developers who encounter the same issue as mine.

HTML5 App Cache not working with POST requests

I'm working on a web application and I went through the necessary steps to enable HTML5 App Cache for my initial login page. My goal is to cache all the images, css and js to improve the performance while online browsing, i'm not planning on offline browsing.
My initial page consist of a login form with only one input tag for entering the username and a submit button to process the information as a POST request. The submitted information is validated on the server and if there's a problem, the initial page is shown again (which is the scenario I'm currently testing)
I'm using the browser's developers tools for debugging and everything works fine for the initial request (GET request by typing the URL in the browser); the resources listed on the manifest file are properly cached, but when the same page is shown again as a result of a POST request I notice that all the elements (images, css, js) that were previously cached are being fetched form the server again.
Does this mean that HTML5 App Cache only works for GET requests?
Per http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#the-application-cache-selection-algorithm it appears to me that only GET is allowed.
In modern browsers (which support offline HTML), GET requests can probably be made long enough to supply the necessary data to get back data you need, and POST requests are not supposed to be used for requests which are idempotent (non-changing). So, the application should probably be architected to allow GET requests if it is the kind of data which is useful offline and to inform the user that they will need to login in order to get the content sent to them for full offline use (and you could use offline events to inform them that they haven't yet gone through the necessary process).
I'm having exactly the same problem and I wrote a wrapper for POST ajax calls. The idea is when you try to POST it will first make a GET request to a simple ping.php and only if that is successful will it then request the POST.
Here is how it looks in a Backbone view:
var BaseView = Backbone.View.extend({
ajax: function(options){
var that = this,
originalPost = null;
// defaults
options.type = options.type || 'POST';
options.dataType = options.dataType || 'json';
if(!options.forcePost && options.type.toUpperCase()==='POST'){
originalPost = {
url: options.url,
data: options.data
};
options.type = 'GET';
options.url = 'ping.php';
options.data = null;
}
// wrap success
var success = options.success;
options.success = function(resp){
if(resp && resp._noNetwork){
if(options.offline){
options.offline();
}else{
alert('No network connection');
}
return;
}
if(originalPost){
options.url = originalPost.url;
options.data = originalPost.data;
options.type = 'POST';
options.success = success;
options.forcePost = true;
that.ajax(options);
}else{
if(success){
success(resp);
}
}
};
$.ajax(options);
}
});
var MyView = BaseView.extend({
myMethod: function(){
this.ajax({
url: 'register.php',
type: 'POST',
data: {
'username': 'sample',
'email': 'sample#sample.com'
},
success: function(){
alert('You registered :)')
},
offline: function(){
alert('Sorry, you can not register while offline :(');
}
});
}
});
Have something like this in your manifest:
NETWORK:
*
FALLBACK:
ping.php no-network.json
register.php no-network.json
The file ping.php is as simple as:
<?php die('{}') ?>
And no-network.json looks like this:
{"_noNetwork":true}
And there you go, before any POST it will first try a GET ping.php and call offline() if you are offline.
Hope this helps ;)

Resources