Home >Web Front-end >JS Tutorial >How to POST URL-Encoded Form Data with AngularJS's $http Service Without jQuery?

How to POST URL-Encoded Form Data with AngularJS's $http Service Without jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 17:12:14482browse

How to POST URL-Encoded Form Data with AngularJS's $http Service Without jQuery?

POSTing URL-Encoded Form Data with $http without jQuery

When making AJAX calls using AngularJS' $http service, you may encounter challenges when sending form data that requires URL-encoding. This can be particularly frustrating for those seeking a jQuery-free solution.

Problem

Attempts to send form data using Angular's $http service with the following approaches have resulted in failures:

  • data: {username: $scope.userName, password: $scope.password}
  • params: {username: $scope.userName, password: $scope.password}
  • data: JSON.stringify({username: $scope.userName, password: $scope.password})

Solution

To successfully POST URL-encoded form data, you need to transform the data object into URL parameters. According to Ben Nadel, Angular by default serializes the outgoing data as JSON and posts it with "application/json" content-type.

To change this behavior and post form data, update the code as follows:

data: {username: $scope.userName, password: $scope.password}
transformRequest: function(obj) {
    var str = [];
    for(var p in obj)
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
},

This code converts the JavaScript object into a URL-encoded string, allowing for successful POSTing of form data without jQuery.

Enhanced Solution with Angular 1.4

For AngularJS v1.4 and later, utilizing the newly added services provides an even simpler solution:

data: {username: $scope.userName, password: $scope.password},
headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
}

The above is the detailed content of How to POST URL-Encoded Form Data with AngularJS's $http Service Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn