ExyTab
ExyTab

Reputation: 557

Angularjs. Jsonp. Sending data

I try to send data using JSONP request in AngularJS.

$http({ method: 'jsonp', 
url: 'http://test.local/?callback=JSON_CALLBACK',  /// Add '?callback=JSON_CALLBACK'
data: JSON.stringify(request) })
.success(function (data, status, headers, config) { });

Is this possible?

Upvotes: 1

Views: 13426

Answers (2)

Manuel Ebert
Manuel Ebert

Reputation: 8559

Late answer, but: data only works for POST requests. However you can't make a POST request with JSONP -- the way it works is it inserts a <script> tag into your DOM with src set to the URL of the request; when your browser evaluates the script it will call the callback parameter (Angular basically replaces JSON_CALLBACK by a pointer to your success function).

TL;DR: the only way you can send stuff to the server using JSONP is using the params key in the config.

Upvotes: 6

Nicolas ABRIC
Nicolas ABRIC

Reputation: 4935

Yes it's possible see the $http.jsonp function. In short you should do something like

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK')
  .success (function(data, ...) {
    //your data here
    ...
  })

Please be aware that you must set callback=JSON_CALLBACK as a query parameter of your http call in order for angular to do its magic.

To send data along with your request it will depend if you want query parameters (1), request message data (2) or both (3).

Case 1 :

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {params : Object | String})

as per documentation "Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified."

Case 2 :

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {data : Object | String})

Case 3 :

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {params : Object | String, data : Object | String})

Upvotes: 9

Related Questions