At the moment i am using below code and it is working fine.
$scope.processForm = function($scope.formData) {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
Now i have one small requirement. I need to pass user id(uid) along with the form data.
In Jquery it is quite simple but I am new to angular and don't have much experience.
Any advise how i can pass the additional data in Angular.
Thanks
You can encapsulate your formData with your uid parameter togheter in an object expl :
var allData={'formData': $scope.formData, 'uid': $scope.uid}
And then pass in the allData Object to your post method data : allData.
If you encounter any problem getting data in you process.php (undefined data for example), you should let Angular pass data with content type application/json (default behavior of angularjs) and in your process.php you do like this :
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
Note that it will be great if you test with some static values first ( 'uid' : 2 ) to make sure that it works fine
you can send an object (associative array in php ) in $http data parameter:
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'userid':userid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
see https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way for details on how to get data in php side
Related
Super confused about this one. I have a website that asks the user to enter the courses they took in highschool, and based on that it retrieves a list of eligible careers from the database as JSON data. Later, the user selects their personality type, and that list of careers is supposed to be filtered further more in the backend to get the new eligible careers.
Retrieving list of careers the first time based on courses:
if(form.$valid) {
$http({
method : 'POST',
url : 'https://some-django-url/get-careers-first-round/',
data : $.param($scope.formData), // pass in courses
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data){
$scope.careers = $scope.$eval( careers );
});
}
Sending list of careers again to the backend (Django) to do extra filtering. I am stuck here. I attempted to do the following:
$http({
method : 'POST',
url : 'https://some-django-url/ajax/get-careers-second-round/',
data : $.param($scope.careers), // ???
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data){
$scope.careers = $scope.$eval( data.careers );
});
But this is not sending the careers list properly. What's wrong with my code? And is that the recommended way to pass a previously retrieved array back to the backend?? (considering I am using Django as a backend framework) ?
Thanks a bunch in advance!
Preface: I am using AngularJS 1.5.9.
When writing my service, this code works when posting to the server:
var request = {
url: '/connect/token',
method: 'POST',
data: $httpParamSerializer(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http(request).then(function(response) {});
However, it seems counterintuitive to use data when $http has the usage argument params, with the following definition as per AngularJS's documentation:
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
As you can see, the documentation specifies that this argument is meant to be used only for GET requests. I confirmed as much when I attempted to use the params argument with my POST request:
var request = {
url: '/connect/token',
method: 'POST',
params: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http(request).then(function(response) {});
When you submit the POST request in this way, you get the following response from the server:
{
"error":"invalid_request",
"error_description":"A malformed token request has been received: the mandatory 'Content-Type' header was missing from the POST request."
}
In other words, if I don't use the data argument and invoke the param serializer service on the params I want to pass in, my custom service won't set the Content-Type header on my request, I've confirmed this in the network tab of the web inspector.
TLDR; Why do I have to use the data argument and serialize the params instead of just using the params argument directly? And why is the content type I specify ignored when I do use the params argument?
Use params option for GET requests.
With params option you can set URL query string parameters like baseurl.com?myParam=something
What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
when I post Object data from app.js to homecontroller using two different methods (complete $http.post and shorthand $http.post) like below:
var book = {
"title" : $scope.addTitle,
"publisher" : $scope.publisherSelected[0],
"authors" : $scope.authorsSelected,
"genres" : $scope.genresSelected
};
//This one posts data successfully:
$http({
method : 'POST',
url : '../administrator/addBook',
data : book,
}).
//This one fails:
$http.post("../administrator/addBook", {
data : book
},
What is the difference between them? I thought they were the same.
When you use the shorthand post method, the second argument itself is the data, so no need to add a wrapper {data:book} there (Adding it must be breaking your contract with the server, you can inspect the data being sent using the network console of the browser). So the difference between both the apis is only the way you set the configuration.
So
$http({
url: 'someurl',
data: someData, //Post data 2nd argument in http.post
method: 'POST', //implicit in case of http.post
config: { //This goes in as third argument
headers: someheadersObj,
transformRequest : someTransformFunc,
...
}
});
will be
$http.post('someurl', book, {
headers: someheadersObj,
transformRequest : someTransformFunc,
...
})
i.e, you need to do just this:
$http.post("../administrator/addBook", book)
Documentation
post(url, data, [config]);
Read this for all the configuration available.
I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.