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?
If it is a form try changing the header to:
and if it is not a form and a simple json then try this header:
The problem is the JSON string format, You can use a simple URL string in data:
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support
application/x-www-form-urlencoded
, then throw it away ... hopefully AngularJS does !Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises
.then(success, error)
when dealing with$http
, forget about.sucess
and.error
callbacks (as they are being deprecated)From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
Document for the
encodeURIComponent
can be found hereyou need to post plain javascript object, nothing else
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side