I'm trying to add a post request to a button in my ionic app but I've found that adding the code makes the app useless. Not a single thing responds to any of my taps. Removing the code makes things normal again. This is all I have added:
$scope.powerPrompt = function() {
var pwr = alert("Power On");
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({
method: 'POST',
url: 'url',
data: "string"
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
// handle success things
})
.error(function(data, status, headers, config) {
// handle error things
})
};
If I delete everything inside the powerPrompt function except the var pwr line, the rest of my app works. What's causing this? Do I have a syntax issue?
You are missing a , after the data property
$scope.powerPrompt = function() {
var pwr = alert("Power On");
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({
method: 'POST',
url: 'url',
data: "string",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
// handle success things
})
.error(function(data, status, headers, config) {
// handle error things
})
};
Related
I am unable to fetch json data from $http post method in angularjs
I had try following code in my controller file
var sectionTypeVM = new Object();
sectionTypeVM.sessionid = 'Session';
sectionTypeVM.query = 'where LOB group by Report_Source_Type,Report_Object_Type';
// alert(JSON.stringify(sectionTypeVM));
$http({
method: 'post',
url: 'http://testserver/search',
dataType: 'json',
data: JSON.stringify(sectionTypeVM),
headers: { 'Content-Type': 'application/json' }
}).success(function(data, status, headers, config) {
alert('success');
alert(data);
})
.error(function(data, status, headers, config) {
alert('error');
alert(data+ status + headers + config );
});
My $http request return error function when called.
I am using AngularJS v1.2.16
Thanks
Gajanan
I am trying to achieve a login functionality using Angular JS on front-end and PHP + Zend on the back-end. Below is the code snippet of the angular js controller. This doesn't redirect the user to the appropriate page and while debugging, the control doesn't enter the success part but enters the error part with data being NULL. However if I put the $http part outside the function, atleast the control enters the success part with data being that of the next page to be redirected.
What could i be missing and what is the correct way to achieve the redirection?
In the below code the control doesn't enter the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$scope.authenticatelogin = function () {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
In the below code the control enters the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: 'abc#abc.com', password: 'xyzxyz', rememberMe: ''})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
});
I would rather go for success/error callbacks to be part of the then method.
From angular documentation for version 1.4.5:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Try this one, although if you say that your code works outside the closure, it might not be the solution you are looking for:
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).then(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}, function(data, status, headers, config) {
$scope.status = status;
});
$scope.getPostItem = function(itemLength){
// load post items ajax
$http({
method: 'GET',
url: '../Rresume/loadPostItem.php?itemLength=itemLength'}).
success(function(data, status, headers, config) {
});
trying to pass itemLength into the url, possible? I got a null result. But when I put itemLength=4 it work.
scope.getPostItem = function(itemLength){
// load post items ajax
$http({
method: 'GET',
url: '../Rresume/loadPostItem.php?itemLength=' + itemLength}).
success(function(data, status, headers, config) {
});
Try this
The following $http request executes successfully, yet the PHP script on the other end receives an empty $_POST array when it should receive 'test' and 'testval.' Any ideas?
$http({
url: 'backend.php',
method: "POST",
data: {'test': 'testval'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
If you wan to send just that simple data, try this:
$http({
url: 'backend.php',
method: "POST",
data: 'test=' + testval,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
And php part shoul be like this:
<?php
$data = $_POST['test'];
$echo $data;
?>
It is working for me.
This is a common issue with AngularJS.
The first step is to change the default content-type header for POST request:
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded; charset=UTF-8;";
Then, using an XHR request interceptor, it is necessary to serialize properly the payload object:
$httpProvider.interceptors.push(['$q', function($q) {
return {
request: function(config) {
if (config.data && typeof config.data === 'object') {
// Check https://gist.github.com/brunoscopelliti/7492579
// for a possible way to implement the serialize function.
config.data = serialize(config.data);
}
return config || $q.when(config);
}
};
}]);
In this way, payload data will be again available in the $_POST array.
For more info about XHR interceptor.
Another possibility, it is to mantain the default content-type header, and then server side parse the payload:
if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
$_POST = json_decode(file_get_contents("php://input"), true);
}
More simplified way:
myApp.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) { return data; }
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
Remove the following line, and the preceding comma:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
And then the data will appear in $_POST. You only need that line if you are uploading a file, in which case you'll have to decode the body to get the data vars.
I found my solution here http://www.peterbe.com/plog/what-stumped-me-about-angularjs. There is a piece of code in the "AJAX doesn't work like jQuery" section, which solved my problem.
Here's the code for the entire $http implementation:
$http({
url: jsurl('profile.login'),
method: 'POST',
data: $.param({
username: $scope.username,
password: $scope.password,
csrfmiddlewaretoken: $.cookie('csrftoken')
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function (data) {
$scope.success = true;
}).
error(function (data) {
$scope.success = false;
$scope.errors = data.errors;
});
The issue is that data in $http.error is a string despite returning the following response:
Content-Type:application/json; charset=UTF-8
Body: {"errors":{"username":{"messages":[["Pleaseenteryourusername."]]},"password":{"messages":[["Pleaseenterpassword."]]}},"success":false}
In jQuery I would normally use $.parseJSON() however I keep hearing about how I shouldn't use jQuery code within Angular code (I've yet to understand why this is) so I'm wondering if there's a more Angular canonical method to parsing error response to JSON.
Yes, there is angular.fromJson utility function. See http://docs.angularjs.org/api/angular.fromJson