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

3
  • 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 headers like shown here or at runtime like the docs for $http show. Similar question and answer here as well Commented Oct 11, 2014 at 0:26
  • You shouldn't use angular as an extension to jQuery... Commented Oct 11, 2014 at 1:21
  • thanx @intothev01d for pointing out the content type difference... Commented Oct 11, 2014 at 19:46

1 Answer 1

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;
        });
    });
Sign up to request clarification or add additional context in comments.

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.