[javascript] AngularJS passing data to $http.get request

I have a function which does a http POST request. The code is specified below. This works fine.

 $http({
   url: user.update_path, 
   method: "POST",
   data: {user_id: user.id, draft: true}
 });

I have another function for http GET and I want to send data to that request. But I don't have that option in get.

 $http({
   url: user.details_path, 
   method: "GET",
   data: {user_id: user.id}
 });

The syntax for http.get is

get(url, config)

This question is related to javascript angularjs javascript-framework

The answer is


Solution for those who are interested in sending params and headers in GET request

$http.get('https://www.your-website.com/api/users.json', {
        params:  {page: 1, limit: 100, sort: 'name', direction: 'desc'},
        headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
    }
)
.then(function(response) {
    // Request completed successfully
}, function(x) {
    // Request error
});

Complete service example will look like this

var mainApp = angular.module("mainApp", []);

mainApp.service('UserService', function($http, $q){

   this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {

        var dfrd = $q.defer();
        $http.get('https://www.your-website.com/api/users.json', 
            {
                params:{page: page, limit: limit, sort: sort, direction: direction},
                headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
            }
        )
        .then(function(response) {
            if ( response.data.success == true ) { 

            } else {

            }
        }, function(x) {

            dfrd.reject(true);
        });
        return dfrd.promise;
   }

});

For sending get request with parameter i use

  $http.get('urlPartOne\\'+parameter+'\\urlPartTwo')

By this you can use your own url string


You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

Starting from AngularJS v1.4.8, you can use get(url, config) as follows:

var data = {
 user_id:user.id
};

var config = {
 params: data,
 headers : {'Accept' : 'application/json'}
};

$http.get(user.details_path, config).then(function(response) {
   // process response here..
 }, function(response) {
});

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to javascript-framework

What is the difference between React Native and React? Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate Angular JS break ForEach AngularJS passing data to $http.get request AngularJs ReferenceError: $http is not defined Difference between the 'controller', 'link' and 'compile' functions when defining a directive Pass variables to AngularJS controller, best practice? How to generate UL Li list from string array using jquery? jQuery: Check if div with certain class name exists Get epoch for a specific date using Javascript