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');
})
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.
I'm following this tutorial for having banner ads in my android application.
https://blog.nraboy.com/2014/06/using-admob-ionicframework/
The problem is that I get an error callback from the plugin which is only telling me :
Invalid action
I ran the cordova plugin add for the plugin, I modified the admob publisher id, I used the sample code from the tutorial right above but it always get stuck in the second callback function which is the error case callback.
Here is the code I used :
var admobApp = angular.module('myapp', ['ionic'])
.run(function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
if(window.plugins && window.plugins.AdMob) {
var admob_key = device.platform == "Android" ? "ANDROID_PUBLISHER_KEY" : "IOS_PUBLISHER_KEY";
var admob = window.plugins.AdMob;
admob.createBannerView(
{
'publisherId': admob_key,
'adSize': admob.AD_SIZE.BANNER,
'bannerAtTop': false
},
function() {
admob.requestAd(
{ 'isTesting': false },
function() {
admob.showAd(true);
},
function() { console.log('failed to request ad'); }
);
},
function() { console.log('failed to create banner view'); }
);
}
});
});
I am make an Android (Native app) with help of(JQuery Mobile and Phonegap) in which i want to share the data on facebook please help me out how i will do these
IN HTML5:-
<div data-role="content">
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
Share
</div>
in this app i want to share the data which is there in textarea should display on facebook when i click button
without using any plugin if we can do please help me out or with plugin we have to do then tell me how i can do step by step process
Share data on Facebook through PhoneGap
Use Child browser OR InAppbrowser plugin then add follwing code
function FBConnect()
{
if(window.plugins.childBrowser == null)
{
ChildBrowser.install();
}
}
$("#share_on_wall").live("click", function(event){
if(event.handled !== true){
var fb = FBConnect.install();
fb.postFBWall(desc, post_url, vPromotionPicture_url, vTitle);
event.handled = true;
}
return false;
});
FBConnect.prototype.postFBWall = function(message, urlPost, urlPicture, vTitle)
{
if(urlPicture == undefined)
urlPicture = "";
urlPost ="";
var url = "https://www.facebook.com/dialog/feed?app_id=your_app_id&link="+encodeURIComponent(urlPost)+"&picture="+encodeURIComponent(urlPicture)+"&name="+encodeURIComponent(vTitle)+"&caption=&description="+encodeURIComponent(message)+"&redirect_uri=your_redirect_uri";
var ref = window.open(url, 'random_string', 'location=no');
ref.addEventListener('loadstart', function(event) {
});
ref.addEventListener('loadstop', function(event) {
console.log(event.type + ' - ' + event.url);
var post_id = event.url.split("post_id=")[1];
var cancel_url = event.url.split("#")[0];
if(post_id != undefined){
setTimeout(function() {
ref.close();
}, 5000);
}
if(cancel_url != undefined && cancel_url == your_redirect_uri){
setTimeout(function() {
ref.close();
}, 1000);
}
});
ref.addEventListener('exit', function(event) {
});
}