0

I'm trying to send some simple data to the server. I take the originally received server data used to create dynamic forms, quickly clean up unnecessary keys using delete formData['not_needed'], and then I wanted to add the model that has been created before posting to the server, but when I check the data objects model key that I'm trying to add it is always an empty string. I can either send one or the other, but can't seem to add one object to another as a key-value pair.

// Abridged version
var formData = $scope.responseData; // original server data to build forms
delete formData['config_data']; // remove unnecessary keys

formData.model = $scope.formModel; // add model key

$http.post('/restful/api', formData).then(function(success) {...}, function(error) {...});

The output of passed data from the server looks like:

{ id: "1", type: "type_of_form", name: "name_of_package", model: "" } // model always empty

Is this an issue using $scope?

UPDATE

Even when I hardcode the outgoing keys:

var packageData = {
    "packageid": $scope.formData.id, // makes it to server
    "desc": $scope.formData.desc, // also makes it to server
    "data": $scope.formModel // is just an empty string
}

But formModel filled from some dumby form data when logged to console and printed out to the screen using a filter { formModel | json } looks like:

formModel = {
  "document_date": "1234",
  "first_name0": "1",
  "first_name1": "2",
  "first_name2": "3",
  "first_name3": "4"
}
mtpultz
  • 17,267
  • 22
  • 122
  • 201

1 Answers1

0

It could be that you're running into the by-now famous "AngularJS cannot form-URL-encode data it POSTs by default" pitfall; if so, you'll need to do this before you try and post:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];
    for (key in data) {
      if (data.hasOwnProperty(key)) {
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
      }
    }
    return result.join("&");
  });
}]);

via How can I post data as form data instead of a request payload?

Community
  • 1
  • 1
T.W.R. Cole
  • 4,106
  • 1
  • 19
  • 26