2

I'm trying to test posting data to the server using $http.post. The backend is built with laravel.

I'm just learning Angular so there isn't anything complicated going on. When I try to post to /api and I get a 404 error in my browser console. If I open the URl in a browser it does exist. The page itself just returns some json.

Here's the HTML:

<ul>
    <li ng-repeat="brand in brands">
        <input type="checkbox" name="{{brand.brand_name}}" ng-model="brand.checked" ng-change="getSelectedBrands()">
        {{ brand.brand_name }}
    </li>
</ul>   

And the part of the controller responsible for posting the data:

$scope.getSelectedBrands = function() {  
    var data = $filter('filter')($scope.brands, {checked: true});
    $http.post('/api', data).success(function(data, status, headers) {
        //do something
    });        
}

Why it posts on every checkbox check or uncheck is that these checkboxes will be filtering results from the database once I get to that stage.

Any help would be greatly appreciated.

Thanks!

EDIT WITH NETWORK TAB RESULT: Network Tab

BarryWalsh
  • 1,300
  • 4
  • 14
  • 36
  • can you open the network tab in devtools and show us the request? – Ilan Frumer Jan 15 '14 at 15:15
  • You didn't share your server side code, but read this http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/. Or my blog post about similar problems with Coldfusion: http://www.jeffryhouser.com/index.cfm/2013/10/1/Calling-a-ColdFusion-CFC-from-AngularJS I suggest you use a package sniffer to see what is being sent from your UI to the server. If you had the same problem as me; then this is your solution: `$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';` – JeffryHouser Jan 15 '14 at 15:16
  • @IlanFrumer Added a screenshot from the network tab to my question. Thanks – BarryWalsh Jan 15 '14 at 15:26
  • can you post your server code? – ilmatic Jan 15 '14 at 15:26
  • @Reboog711 The server side code is just a route that return JSON from the server. It works on it's own so I didn't think it was too relevant to the issue. Where does that line go? Thanks! – BarryWalsh Jan 15 '14 at 15:28
  • @Reboog711 Actually you're right I should have shared the laravel route. – BarryWalsh Jan 15 '14 at 15:29
  • Since you're seeing a 404 error, isn't it likely that the URL you're posting to is wrong? – JeffryHouser Jan 15 '14 at 15:31
  • @Reboog711 The URL wasn't wrong. It was that I was using GET instead of POST in my laravel route. – BarryWalsh Jan 15 '14 at 15:52

2 Answers2

4

If you open the URI in a browser you are performing a GET request. It's possible your backend is setup to respond to GET routes but not POST.

ilmatic
  • 565
  • 3
  • 11
2

as per Jeff's comment, you may need to add following to your controller

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
Abhijit Gaikwad
  • 3,072
  • 28
  • 37