Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a straightforward form using Angular

Using angular, I want to submit a form and store the response. My code looks something like this:

<form ng-controller="myController" action="myAction" method="POST">
    <input type="text" name="name" />
    <input type="submit" ng-click="submit" />
</form>

<script>
    function myController($scope, $http) {
        $scope.submit = function() {
            $http.post(url, data).success(function(data) {
                $scope.result = data;
            });
        }
    }
</script>

How do I get url and data to be the form action and inputs, respectively? I don't want to send JSON, I want the server side to see this is a regular HTML form submit.

like image 208
rjsang Avatar asked May 24 '26 17:05

rjsang


1 Answers

Thank, @Vincent Ramdhanie, for pointing me in the right direction. Here's what I ultimately did, using plenty of jQuery thrown in:

function myController($scope, $http) {
    $('form').submit(function() {
        return false;
    }); 

    $scope.submit = function() {
        form = $('form');
        data = form.serialize();
        url = form.attr('action')

        $http.post(url, data, 
            { headers: 
                { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
            }).success(function(data) {
                $scope.result = data;
            }
        );
    }
}
like image 97
rjsang Avatar answered May 26 '26 06:05

rjsang