Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to $http in angularjs?

Assume that I have two input boxes with corresponding ng-model as fname and lname. If I call http request as :

$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}}) 

will it call to the url :

/search?fname=fname&lname=lname 

The error I am getting at the backend(python) is :

cannot concatenate str and nontype objects. 

Are these parameters not sent as strings? If not, how to get around with this?

like image 853
exAres Avatar asked Sep 20 '13 06:09

exAres


People also ask

How do we pass data and get data using http in angular?

get request Method Syntax: $http. get(url, { params: { params1: values1, params2:values2, params3:values3...... } });

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.


2 Answers

Here is how you do it:

$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})     .then(function (response) { /* */ })... 

Angular takes care of encoding the parameters.

Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData} is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).

like image 86
sleblanc Avatar answered Oct 10 '22 02:10

sleblanc


Build URL '/search' as string. Like

"/search?fname="+fname"+"&lname="+lname 

Actually I didn't use

 `$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})`  

but I'm sure "params" should be JSON.stringify like for POST

var jsonData = JSON.stringify(     {         fname: fname,         lname: lname      } ); 

After:

$http({   method:'GET',   url:'/search',   params: jsonData }); 
like image 39
Maxim Shoustin Avatar answered Oct 10 '22 02:10

Maxim Shoustin