AJAX post request with Angularjs

Asked

Viewed 4,683 times

5

Hello,

I wanted to know how I make a requisition POST for a url with Angularjs and also wanted to know how I transform a normal javascript object for a json, to send in this request.

2 answers

5


You can use the service $http angularjs.

  1. In your controller, declare the service dependency $http:

    .controller('TesteCtrl', ['$scope', '$http', function($scope, $http){ ...
    
  2. Your javascript object (jsonObj in this example) can be sent directly. Angular will automatically serialize before sending it:

    var jsonObj = { campo1: "teste", campo2 : 123 };
    
    $http.post('/url-da-requisicao', jsonObj)
    .success(function(data, status, headers, config) {
      // sucesso! 
      // data agora contém o que foi retornado pelo servidor
      })
    .error(function(data, status, headers, config) {
      // erro!
      // você pode verificar o parâmetro "status" para ver o código HTTP do erro
    });
    

Note: By default, the Content-type post used by angular is application/json. If your server is using PHP, you won’t be able to directly read the data received in JSON. See here a solution.

4

In Angularjs you can submit AJAX requests in several ways:

  • AJAX calls via the $http service.
  • JSONP calls via the $http service.
  • REST type calls.

Angularjs & JSONP

Example of a JSONP call with the URL set:

var url = http://jenkov.com/theService.json?callback=JSON_CALLBACK "; 
var responsePromise = $ http.jsonp (url, 
             {params: { 
                   p1: "v1" 
                  ,p2: "v2" 
                } 
              } 
            ); 

responsePromise.success (function (data) { 
    // faz alguma coisa com o objeto JavaScript
    // (no parâmetro "data"). 
});

Study: https://docs.angularjs.org/api/ng/service/$http

Browser other questions tagged

You are not signed in. Login or sign up in order to post.