Grateful Grateful - 1 month ago 8
jQuery Question

$http.post vs $.getJSON response?

From an angular app, when I send a post request using jQuery as follows, ...

this.login = function (email, password) {
return $.getJSON(FOO_URL, {
email: email,
password: password
});
}


... my response is perfectly fine.

Object {result: "ok", key_one: result_one, key_two: result_two, ...}


However, when I try to do the same thing using angular's
$http
as follows, ...

this.login = function (email, password) {
return $http.post(FOO_URL, {
email: email,
password: password
});
}


... my response data is completely empty.

Object {data: "", status: 200, config: Object, statusText: "OK"}


Why is my response data empty with angular
$http
?

Answer

jQuery's $.getJSON will not issue a POST request. It can only do GET.

To make it exactly the same, you'll want to pass the data as params...

$http.get(FOO_URL, {
    params: {
        email: email,
        password: password
    }
})

See https://docs.angularjs.org/api/ng/service/$http#usage


To send a POST request with data formatted as application/x-www-form-urlencoded which, if you're using PHP's $_REQUEST (or $_POST) you will need to do, see this answer ~ http://stackoverflow.com/a/30970229/283366

Short answer, inject $http and $httpParamSerializer and use

$http({
    method: 'POST',
    url: FOO_URL,
    data: $httpParamSerializer({email: email, password: password}),
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})