I'm developing an android app that needs to detect internet connection and if the device has no internet connection there will be an alert that the device has no internet connection.
here is my code:
<script>
var lform = $("#loginform");
function verifyfirst(){
if($( "#txtusername" ).val() == "" || $( "#txtpassword" ).val() == "")
{
return;
}
else
{
$.mobile.loading("show");
$.getJSON("http://url/verifyfirst.php?callback=?", lform.serialize(),function(data)
{
if (data.verified == "v1")
{
localStorage.setItem("datausername", data.txtusername);
if (localStorage.getItem("datausername") == "admin")
{
location.href="admin.html";
}
else
{
//$.mobile.changePage( "menu.html", { changeHash: true });
location.href="menu.html";
}
}
else
{
$("#popuptext").html("<b>The account you've entered is not associated with Happy Au Pair. Please check your username or password.</b>");
$( "#popupAfter" ).popup( "open", {
positionTo: "window",
transition: "pop" });
$.mobile.loading("hide");
}
}).fail(function(data){
$("#popuptext").html("<b>There is a problem with your login, please try again later.</b>");
$( "#popupAfter" ).popup( "open", {
positionTo: "window",
transition: "pop"});
$.mobile.loading("hide");
});
}
}
</script>
I tried it combining it here but it's not working:
<script>
var online = navigator.onLine;
if(online) {
//I placed the ajax here
} else {
alert("Internet Connectivity is not available.");
}
</script>
Please help me achieve this. And I'm using build.phonegap.com in exporting apk file.
Thanks in advance.
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
you will get online or offline and can use it accordingly. Also you test it by making an ajax call
$.ajax({
url: url,
type: 'GET',
contentType: "application/json;charset=utf-8",
success: function (data) {
// Yor success logic
},
error: function (request) {
// alert(request.responseText);
// alert(request.status);
if(request.status==0)
{
alert("Please connect to the internet");
}
}
});
try sending dummy ajax request before you send an actual request
$.ajax({
url: 'TestUrl',
type: 'GET',
success: function (data) {
// Go ahead with you request
},
error: function (x, y, z) {
if (x.status == 0) {
alert("Please connect to the internet");
}
else{
alert("Other Error Occured")
}
}
});
Phonegap also have online and offline whish is fired when there is a change in connectivity
Related
I'm trying to submit form with files with the following call :
var formData = new FormData(this);
$.ajax({
cache: false,
processData: false,
contentType: false,
data: formData,
type: "POST",
url: "api/action",
success: function (msg) {
console.log(msg);
},
error: function (msg) {
console.log(msg);
}
});
it works fine in web browser including safari
it works fine in android OS
but in IOS the call failed and return error 400
var $form = $(this); // <- change this depending on your scope/usecase
$form.find('input[name][type!="file"], select[name], textarea[name]').each(function(i, e) {
if ($(e).attr('type') == 'checkbox' || $(e).attr('type') == 'radio') {
if ($(e).is(':checked')) {
formData.append($(e).attr('name'), $(e).val());
}
} else {
formData.append($(e).attr('name'), $(e).val());
}
});
// [type="file"] will be handled separately
$form.find('input[name][type="file"]').each(function(i, e) {
if ($(e)[0].files.length > 0) {
formData.append($(e).attr('name'), $(e)[0].files[0]);
}
});
I'm using the following code to show a message when there is no network. It works well when testing the app in airplane mode. However, it always shows the popup even when there is network when the app code start (rejection.status === 0). How to workaround it?
.config(function($provide, $httpProvider) {
$provide.factory('httpInterceptor', function($q, $injector) {
return {
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
var interactiveService = $injector.get('interactiveService');
if (rejection.status === 0 || rejection.status === -1) {
interactiveService.showPopup('The internet is disconnected on your device.' + rejection.status);
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('httpInterceptor');
})
If it helps try this
.config(function($provide, $httpProvider) {
$provide.factory('httpInterceptor', function($q, $injector) {
return {
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
var interactiveService = $injector.get('interactiveService');
/************** New code starts*******/
var networkState = navigator.connection.type;
if(networkState === Connection.NONE){
interactiveService.showPopup('The internet is disconnected on your device.' + rejection.status);
}
/************** New code ends*******/
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('httpInterceptor');
})
I am trying to log my users with Facebook, but can't figure out how to do it.
This is the code I have so far :
facebookConnectPlugin.getLoginStatus(
function(status) {
if (status.status != "connected") {
facebookConnectPlugin.login(
['public_profile', 'email'],
function(success) {
console.log("Success", success);
},
function(error) {
console.log("Error", error);
}
);
}
else {
console.log("logging status : ", status.status);
}
},
function(error) {
console.log("Getting logging status failed : ", error);
}
);
On my Android device, I do not have the Facebook app installed, and I am not logged into Facebook on any browser.
I would expect the facebookConnectPlugin.login() method to popup the login form, but instead this is what it returns :
Which basically means : "You did not enter. You are not connected to Facebook. Enter Facebook and try again".
I looked into this Meteor plugin to see how they were doing it, but they respect the exact same logic.
I am not sure what to do from here. Any suggestion is most welcome !
you can try code for get Login Status read more here
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getLoginStatus(
function (status) {
alert("current status: " + JSON.stringify(status));
}
);
};
you can try code for get User Profile.
facebookConnectPlugin.login( ["public_profile","email"],
function (response) {
if(response.authResponse.userID!=''){
facebookConnectPlugin.api(response.authResponse.userID+"/?fields=id,email,first_name", ["public_profile"],
function (response) {
console.log('SUCCESS:'+response);
alert('first_name : '+response.first_name+',email:'+response.email+',id:'+response.id);
},
function (response) {
console.log('ERROR:'+response);
});
}
},
function (response) {
console.log('ERROR:'+response);
});
let me know if its not working...
Firstly, sorry about my english; I am not a native speaker.
Secondly, I'm making an app for Android using the framework Ionic and I'm using Django as an REST API.
I have issues with a factory: the HTTP status from the request in Django is 200 and the database registers the change, but in the app the HTTP status is 0. This happens only in this factory that contains two POST requests. The other POST requests made on the other factories work fine.
To test the app I use Google Chrome (with the command --disable-web-security), Ionic version 1.5.0, Django version 1.8.2, Cordova version 5.0 (I couldn't find which version of AngularJS I'm using). I have the same issues on several mobile devices.
Here are 3 controllers that cause the problem:
.controller('PlanesCtrl', function($scope, $ionicModal, $ionicPopup,$location, Planes, $window) {
$scope.planes = JSON.parse($window.localStorage['planes']);
$scope.usuario = JSON.parse($window.localStorage['user']);
var usuario_id = {
codusuario: $scope.usuario["codusuario"]
};
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
var especie_id = {
codespecie: $scope.mascotaEscogida.codespecie
};
var mascota_id = {
codmascota: $scope.mascotaEscogida.id
};
var data = {
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
}
$scope.ver_plan = function(plan){
Planes.selectChosenPlan(plan.id);
if (plan.suscrito == 0){
$location.path("/app/planes/" + plan.id);
}
else{
$location.path("/app/entrenar/" + plan.id);
}
};
})
.controller('PlanCtrl', function($scope, $ionicModal,$location, $ionicPopup, $window, Planes) {
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
var mascota_id = {
codmascota: $scope.mascotaEscogida.codmascota
};
$scope.plan = JSON.parse($window.localStorage['planActual']);
var data = {
codplan: $scope.plan.id,
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
};
$scope.suscribir = function(){
var data = {
codplan: $scope.plan.id,
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
};
console.log($scope.plan.id);
console.log($scope.mascotaEscogida.codespecie);
console.log($scope.mascotaEscogida.id);
Planes.suscribir(data, function() {
alert("Su mascota ha sido suscrita al plan con éxito");
} , function() {
} , function() {
console.log("No funciona suscribir en funcion suscribir, PlanCtrl");
});
Planes.buscar(data, function() {
} , function() {
} , function() {
console.log("No funciona buscar en funcion suscribir, PlanCtrl");
});
$location.path("/app/pet/" + mascota_id);
$window.location.reload(true);
};
})
.controller('PetCtrl', function($scope, $stateParams, $filter, $location, Mascota, Planes, $window, $ionicModal) {
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
$scope.usuario_logged = JSON.parse($window.localStorage['user_data']);
$scope.usuario_info = JSON.parse($window.localStorage['user']);
var data = {
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
}
$scope.ver_entrenamientos = function(mascota){
Planes.buscar(data, function() {
alert("Planes encontrados con exito");
} , function() {
alert("La mascotas no posee especie registrada (esto es muy extraño)");
} , function() {
console.log("No funciona buscar en ver_entrenamientos, PetCtrl");
});
$location.path("/app/planes");
$window.location.reload(true);
};
if($scope.usuario_logged === false) {
$location.path('/login');
}
else {
$scope.test = function() {
fecha_hora = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss', '-0300');
var info = {
fecha: fecha_hora,
codmascota: $scope.mascotaEscogida.id,
codusuario: $scope.usuario_info.codusuario
}
Mascota.alimentar(info, function() {
alert("La mascota ha sido alimentada con exito :)");
} , function() {
alert("Lo sentimos, algo ha ocurrido y no podemos registrar la alimentación");
} , function() {
alert("Verifica la conexión a internet");
});
}
}
})
And here is the factory:
.factory("Planes", function($http, $window){
var url = "http://localhost:8000/plan/";
var currentPlanes = function(data){
$window.localStorage['planes'] = JSON.stringify(data);
};
return {
selectChosenPlan: function(id) {
var arregloPlanes = JSON.parse($window.localStorage['planes']);
for (var i = 0; i <= arregloPlanes.length - 1; i++) {
if (parseInt(arregloPlanes[i].id) == id) {
$window.localStorage['planActual'] = JSON.stringify(arregloPlanes[i]);
}
}
},
buscar: function(inf, successFunction, errorFunction, connectionError) {
$http({
method: 'POST',
url: url + 'planes/',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(inf),
timeout: 20000
}).then(function successCallback(response) {
if (response.data.length > 0) {
console.log("buscar" + response.data[0]);
currentPlanes(response.data);
successFunction();
}
else{
currentPlanes(response.data);
errorFunction();
}
}, function errorCallback(response) {
connectionError();
});
},
suscribir: function(inf, successFunction, errorFunction, connectionError) {
$http({
method: 'POST',
url: url + 'suscribir/',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(inf),
timeout: 20000
}).then(function successCallback(response) {
if (response.data.length > 0) {
console.log("suscribir" + response.data[0]);
currentPlanes(response.data);
successFunction();
}
else{
currentPlanes(response.data);
errorFunction();
}
}, function errorCallback(response) {
connectionError();
});
}
};
})
I've made some research in the internet, but all the solutions I've found point to the CORS. If that were the problem, the other factory wouldn't work either, so I don't think that's the problem. Some other answers say that the problem could be in the HTML, on the button that calls 'ver_plan' or 'ver_entrenamiento', but both are set with type="button", so the submit wasn't the problem either. The error happens randomly and I can't find the issue in the flow of events. Sometimes, I even get a 'broken pipe' message from Django, but this also happens randomly.
I know that the JSON answer is valid and has the correct format; I'm out of ideas and I need to solve these issues.
Edit: Also, the line console.log("No funciona buscar en funcion suscribir, PlanCtrl"); doesn't appear in the console when I get the problem.
I found the answer a couple of weeks ago. The problem was
$window.location.reload(true); and $location.path();
It is not necessary the line $window.location.reload(true); if $location.path(); is located inside the factory call. For example:
Planes.buscar(data, function() {
$location.path("/app/pet/" + mascota_id);
} , function() {
} , function() {
console.log("No funciona buscar en funcion suscribir, PlanCtrl");
});
This way, the redirection occurs only if the answer from the server was successful and there is no need to use $window.location.reload(true);
I wish I can give you more details about the reason of the problem but my english is not good enough.
So, I have the following code that all works in the browser but for some reason keeps redirecting me back to login on the actual Android device.
controllers.js
App.controller('LoginController', ['$scope', 'RequestService', '$location', 'OpenFB', '$rootScope', function($scope, RequestService, $location, OpenFB, $rootScope) {
$scope.provider = '';
$scope.loginFacebook = function() {
$scope.provider = 'facebook';
OpenFB.login('email, user_friends').then(
function () {
OpenFB.get('/me').success(function (user) {
localStorage.setItem('fbuser', JSON.stringify(user));
});
localStorage.setItem('provider', 'facebook');
RequestService.get($scope.baseUrl + 'user')
.success(function(data, status, headers, config){
$scope.user = data;
//Set our logged in var
localStorage.setItem('loggedIn', true);
// Check if the user has accepted EULA
if($scope.user.eula == 0) {
$location.path('/eula');
}
else
{
//TODO:Redirect to the users dashboard, when we have the routes.
console.log('EULA Accepted, Redirect somewhere else!');
}
});
},
function (error) {
localStorage.removeItem('loggedIn');
});
};
}]);
I have debugged the above and everything is working as it should, once FB is logged in, it queries the database, sets the user up with the data scraped from Facebook and then checks that data to see if the EULA has been accepted. If not then is should redirect to $location.path('/eula');
routes
.config(function($httpProvider, $stateProvider, $urlRouterProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login', {
url: '/',
templateUrl: 'templates/login.html',
data: {
requireLogin: false
}
})
.state('eula', {
url: '/eula',
templateUrl: 'templates/eula.html',
data: {
requireLogin: true
}
})
.state('accept', {
url: '/accept',
templateUrl: 'templates/accept.html',
data: {
requireLogin: true
}
})
});
as you are using ui-router (standard of ionic), you shall use states.
Replace : $location.path('/eula'); by $state.go('eula');
(and correspondign injected dependency)
Youre problem seems to have something to do with the execution.
OpenFB does not implement promises.
Look at these lines:
OpenFB.get('/me').success(function (user) {
localStorage.setItem('fbuser', JSON.stringify(user));
});
localStorage.setItem('provider', 'facebook');
It might take a while before OpenFB.get returns the result, but your code will execute the following instructions anyway, so you might find yourself in a situation where you're calling:
RequestService.get($scope.baseUrl + 'user')
before OpenFB.get('/me') has finished it's execution.
The best solution is to use ngOpenFB which implement promises: $q promises.
There's a sample here.
Your code should be implemented like this:
ngFB.login({scope: 'email, user_friends'})
.then(function(response){
// response.authResponse.accessToken
return ngFB.api({path: '/me'});
})
.then(function(user){
localStorage.setItem('fbuser', JSON.stringify(user));
localStorage.setItem('provider', 'facebook');
RequestService.get($scope.baseUrl + 'user')
.success(function(data, status, headers, config){
$scope.user = data;
//Set our logged in var
localStorage.setItem('loggedIn', true);
// Check if the user has accepted EULA
if($scope.user.eula == 0) {
return false;
} else
{
return true;
}
})
.error(function (data, status, headers, config) {
return false;
})
})
.then(function(eulaAccepted){
if (eulaAccepted)
{
$state.go('eula');
}
})
catch(function(reason){
localStorage.removeItem('loggedIn');
});
Each call returns a promise and they can be nested. The second .then( gets the result of the second promise (when it's been resolved) ngFB.api({path: '/me'}).
Since that call returns a promise with the object user, you'll be able to read it in the function.
This code:
if($scope.user.eula == 0) {
return false;
} else
{
return true;
}
does not return a promise but it's ok with this type of syntax.
In the third .then( :
.then(function(eulaAccepted){
if (eulaAccepted)
{
$state.go('eula');
}
})
you'll be able to read the value of the previous statement (eula).
Mind you, I haven't tested this code cause I don't have facebook, but the advantage of promises is to avoid indefinite levels of nested code
Ok so solved the issue, in my login check in the .run() method of my app I had a miss placed 'event.preventDefault();' call, once this was moved the works on both the desktop browser and on my device.