Alexander Kozhokar Alexander Kozhokar - 3 months ago 14
Ajax Question

jQuery Ajax request turn into AnularJS $http request

I have such jQuery Ajax request. I need to turn it into an Angular $http request. How can I do that?

$.ajax({
type: "POST",
dataType: "jsonp",
crossDomain: false,
data:{
user: username,
pass: password
},
beforeSend: function (request){
request.setRequestHeader("Accept-Language", languageCode);
},
url: someUrl
})
.done(function (data, textStatus, jqXHR){
console.log(data);
})
.fail(function (jqXHR, textStatus){
console.log("failed");
});


My Angular Implementations

Response {"data" : "", "status" : "200", "config" : .... } Data is empty

login : function (username, password) {
return $http({
method: 'POST',
url: someUrl,
data: {
user: username,
pass: password
},
headers: {
'Accept-Language': languageCode
}
})
}


I succeeded to get data wrapped in JSON_CALLBACK with next request. But I don't know how to call that callback. It is not done automatically. Response looks like {data:"JSON_CALLBACK({mydata})"...}

login : function (username, password) {
var url = someUrl
+ '?callback=JSON_CALLBACK&user=' + username
+ '&pass=' + password;

return $http.post(url);
},

Answer
login : function (username, password) {
  return $http({
    //method: 'POST',
    method: 'JSONP',
    url: someUrl,
    //data: {
    params: {
      user: username,
      pass: password,
      callback: "JSON_CALLBACK"
    },
    headers: {
      'Accept-Language': languageCode
    }
  })
} 

To demonstrate on JSFiddle:

var url="//jsfiddle.net/echo/jsonp/";
var params = { user: "myUser",
               pass: "123456",
               callback: "JSON_CALLBACK"
            };
$http.jsonp(url, { params: params} )
    .then(function onSuccess(response) {
         $scope.response = response;
         console.log(response);
    })

The DEMO on JSFiddle.