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

8
  • can you open the network tab in devtools and show us the request? Commented Jan 15, 2014 at 15:15
  • You didn't share your server side code, but read this victorblog.com/2012/12/20/…. Or my blog post about similar problems with Coldfusion: jeffryhouser.com/index.cfm/2013/10/1/… 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'; Commented Jan 15, 2014 at 15:16
  • @IlanFrumer Added a screenshot from the network tab to my question. Thanks Commented Jan 15, 2014 at 15:26
  • can you post your server code? Commented Jan 15, 2014 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! Commented Jan 15, 2014 at 15:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh that's it. Can't believe it was such a simple mistake. Thanks for your help!
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';

Comments

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.