I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http
from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param
. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params
:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify
:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with
transformRequest
or using external dependencies like jQuery:$httpParamSerializerJQLike
- a serializer inspired by jQuery's.param()
(recommended)$httpParamSerializer
- a serializer used by Angular itself for GET requestsExample usage
See a more verbose Plunker demo
How are
$httpParamSerializerJQLike
and$httpParamSerializer
differentIn general, it seems
$httpParamSerializer
uses less "traditional" url-encoding format than$httpParamSerializerJQLike
when it comes to complex data structures.For example (ignoring percent encoding of brackets):
• Encoding an array
• Encoding an object
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
Example from here.
UPDATE
To use new services added with AngularJS V1.4, see
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
From the $http docs this should work..
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
This is my php back-end laravel controller.
This is my laravel routing
The result in browser is
There is chrome extension called postman. You can use to test your back-end url whether it is working or not. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.
All of these look like overkill (or don't work)... just do this: