1

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?

1

2 Answers 2

9

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})
Sign up to request clarification or add additional context in comments.

4 Comments

problem is in sending data, not in handling recieved answer
I use angular 1.0.7 and Case 2 don't work. Chrome don't send any data. (
Please read the question before answer it. There is no relation between your answer and the OP question.
"You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go". Use this instead: $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
6

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.

1 Comment

"You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go". Use this instead: $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.