0

I am trying to serialize a form and send it over to the server using the http POST method...

i have the code as follows for jquery ..

    var data = $scope.modal.element.find('form').serialize();

    $.ajax({
        type: "POST",
        url: "/user/add.html",
        data: data
    }).success(function(ret){
        $scope.modal.body = $sce.trustAsHtml(ret);
        $http.get("/user/list.json").success(function(data){
            $scope.users = data;
        });
    }); 

the code above works just fine... when i use angular to post the data with the following code...

       var data = $scope.modal.element.find('form').serialize();

       $http.post("/user/add.html", data).success(function(html){
            $scope.modal.body = $sce.trustAsHtml(html);
            $http.get("/user/list.json").success(function(data){
                $scope.users = data;
            });
        });

the server freaks out ... and cannot understand any of the variables that are sent over... the server returns an error saying all my fields are empty ... (it cannot parse it)

i have read some answers where it involves editing the html of the form and use ng-model to get the variables unfortunately i am in liberty of doing that ...

please tell me what the difference between these 2 methods are ... and why one is working and the otherone is not...

PS: i would like to use angular to POST the data

Drmjo
  • 584
  • 1
  • 5
  • 21
  • 1
    More than likely this is because the default POST Content-Type is `application/json` for Angular and `application/x-www-form-urlencoded` for jQuery. You can change this by modifying the defaults for the [$http](https://docs.angularjs.org/api/ng/service/$http#post) headers like shown [here](https://gist.github.com/s9tpepper/3328010) or at runtime like the docs for $http show. Similar question and answer [here](http://stackoverflow.com/questions/12190166/angularjs-any-way-for-http-post-to-send-request-parameters-instead-of-json) as well – Lbatson Oct 11 '14 at 00:26
  • You shouldn't use angular as an extension to jQuery... – Shomz Oct 11 '14 at 01:21
  • thanx @intothev01d for pointing out the content type difference... – Drmjo Oct 11 '14 at 19:46

1 Answers1

1

Try doing it like this:

   var data = $scope.modal.element.find('form').serialize();

   $http({
        method: 'POST',
        url: "/user/add.html",
        data: data,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
   }).success(function(html){
        $scope.modal.body = $sce.trustAsHtml(html);
        $http.get("/user/list.json").success(function(data){
            $scope.users = data;
        });
    });
Josep
  • 12,926
  • 2
  • 42
  • 45