Angularjs $http POST request empty array - javascript

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.

Related

Adding $http request bricks Ionic app

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
})
};

unable to fetch json data from $http post method in angularjs

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

Angular $http.post not returning XML

I am trying to call a web service with angular, but not having much luck. The service takes a POST request with no POST body, and returns XML. I can confirm that the service works with a raw XMLHttpRequest call:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4)
console.log(xhr.responseText); // Returns data
}
xhr.open("POST", "https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML", true);
xhr.send(null);
And with jQuery:
$.ajax({
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
type: "POST",
success: function(data){
console.log(data); // Returns data
},
error: function (hxr, status, errorThrown){
console.log(status);
}
});
However, I'm not getting anything back when I try it with angular's $http service:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
}).success(function(data, status, headers, config){
console.log("data:");
console.log(data); // Returns null
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status); // No errors returned
})
})
EDIT: Using the $http.post shortcut method:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http.post(
'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
).success(function(data, status, headers, config){
console.log("data:");
console.log(data);
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status);
})
})
Note that the $http.post shortcut method has a second data parameter, but I have no data to pass. If I include the parameter as null, Chrome says:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Since the $http.post shortcut method does not complain about missing out the data parameter, I have deliberately missed it out.
I need to be able to make the POST call with no data, as is possible with a raw XMLHttpRequest call, or jQuery's ajax method. What might be going wrong? Thanks!
(NB, the API is public, so don't worry about the API key I've posted. It's a valid API key, which I'll keep active only while this question is open)
Angular by default expecting to get JSON from your server you can change that by adding
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $http) {
$scope.xml = "";
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
headers: {
"Accept": "application/xml"
}
}).success(function(data, status, headers, config) {
console.log("data:");
console.log(data); // Returns null
$scope.xml = data;
}).error(function(data, status, headers, config) {
console.log("error status:");
console.log(status); // No errors returned
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
{{xml}}
</div>
</div>
to your request

ajax and php error : Undefined index: userid in my case

where have I went wrong?
$http({
url: "php/loaduser.php?userid=user_id",
method: "GET",
data: {'user_id':'1'}
}).success(function(data, status, headers, config) {
mydata = [];
mydata = data;
console.log(mydata);
}).error(function(data, status, headers, config) {
// $scope.status = status;
alert(status);
});
my php
echo $_GET['user_id'];
it return Undefined index: user_id
Your call should be like
$http({
url: "php/loaduser.php",
method: "GET",
data: {'user_id':'1'}
})
Or either you can use
$http({
url: "php/loaduser.php?user_id=" + user_id,
method: "GET"
})
In second Method you are directly passing the user_id through the url whereas in the first you are sending it in a variable manner
You are sending in the string user_id.
url: "php/loaduser.php?userid=user_id"
Remove that last query parameter.
Change it to this:
url: "php/loaduser.php"
try this--
$.ajax({
type:"GET",
url:"php/loaduser.php",
data: {'user_id':1}
success:function(data, status, headers, config){
ydata = [];
mydata = data;
console.log(mydata);
}),
error(function(data, status, headers, config) {
// $scope.status = status;
alert(status);
}
});
The key in your URL is wrong: you need to change it from userid to user_id.
Then, you don't need to set the data property, you can include the parameter in your URL like so:
url: "php/loaduser.php?user_id=" + '1'

How to get Access Token from ASP.Net Web API 2 via AngularJS $http?

I try like this:
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password, grant_type: 'password' } }).success(function (data, status, headers, config) {
$scope.output = data;
}).error(function (data, status, headers, config) {
$scope.output = data;
});
then tried changing the grant_type to a param:
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password }, params: { grant_type: 'password' } }).success(function (data, status, headers, config) {
$scope.output = data;
}).error(function (data, status, headers, config) {
$scope.output = data;
});
Still get the dreaded: {"error":"unsupported_grant_type"}
So I do what no AngularJS developer should ever do, resorted to jQuery:
var data = $('#regForm').serialize() + "&grant_type=password";
$.post('/token', data).always(showResponse);
function showResponse(object) {
$scope.output = JSON.stringify(object, null, 4);
$scope.$apply();
};
Which works like a champ... so my question is: how do we replicate the jQuery $.post() call above using AngularJS $http() so we can grab an access token from the OWIN middleware based /token endpoint in ASP.Net Web API 2?
Do this:
$http({
url: '/token',
method: 'POST',
data: "userName=" + $scope.username + "&password=" + $scope.password +
"&grant_type=password"
})
I think, adding the header {headers: { 'Content-Type': 'application/x-www-form-urlencoded' } to your post request would do the trick. It should be something like this:
$http.post(loginAPIUrl, data,
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
You are getting that error because the default implementation of the OWIN OAuth provider is expecting the post to the "/Token" service to be form encoded and not json encoded. There is a more detailed answer here How do you set katana-project to allow token requests in json format?
But you can still use AngularJs you just have to change the way the $http post is made. You can try the answer here if you don't mind using jquery to change your params How can I post data as form data instead of a request payload? Hope that helps.
You can always watch for the requests being made using the developer console in your browser and see the difference in the request.
But by looking at your jquery code &grant_type=password is being passed in the body not the querystring so the $http call should be
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password ,grant_type:password} }).success(function (data, status, headers, config) {
Similar to achinth, but you can still use the $http.post method (+ data is escaped)
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
1) Note the URL: "localhost:55828/token" (not "localhost:55828/API/token")
2) Note the request data. Its not in json format, its just plain data without double quotes.
"userName=xxx#gmail.com&password=Test123$&grant_type=password"
3) Note the content type. Content-Type: 'application/x-www-form-urlencoded' (not Content-Type: 'application/json')
4) When you use javascript to make post request, you may use following:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
See screenshots below from Postman:
Postman Request
Postman Request Header

Categories