0

I am trying to do a post of a form in angular, but the input testValue doesn't get a value.

Any suggestions?

In the angularJs controller:

//FORM
$scope.submitEditSyncSettingsForm = function () {
    if ($("#editSyncSettingsForm").valid()) {

        $http({
            url: "data/postSyncSettings.aspx",
            data: { testValue: 'some value' },
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } 
        }).success(function (data) {
            console.log(data)
        }).error(function (err) { "ERR", console.log(err) })

    }
};

.aspx code behind

public partial class postSyncSettings : System.Web.UI.Page
{
    protected string strResponse = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        strResponse = Request.Form["testValue"];
    }
}
peta
  • 139
  • 3
  • 18
  • `if ($("#editSyncSettingsForm").valid()) {` - Angular has `$invalid` properties for forms with specified attributes - should avoid mixing jQuery and Angular (just a tip, no answer to the question at hand) – tymeJV Oct 23 '14 at 17:58
  • okay, thanks. how would I write it instead? – peta Oct 23 '14 at 18:00
  • Don't mix AngularJS and JQuery! Never! http://stackoverflow.com/a/15012542/3006185 – Artyom Pranovich Oct 23 '14 at 18:00
  • https://docs.angularjs.org/api/ng/type/form.FormController – tymeJV Oct 23 '14 at 18:01
  • Could you provide your server-side part of example? – Artyom Pranovich Oct 23 '14 at 18:02
  • Still off topic, but tried `if ($scope.editSyncSettingsForm.$valid) {` and get the error message: TypeError: Cannot read property '$valid' of undefined. The form looks like this `
    `. Please not that I am using jQuery validation because I am writing an app for a system based on jQuery which has built in validation. So the `default-validate` directive is actually initiating that validation.
    – peta Oct 23 '14 at 18:13
  • @ArtyomPranovich I updated the original post. – peta Oct 23 '14 at 18:16

2 Answers2

1

The problem is the data is still sent in the body as JSON. You'll have to serialize it yourself. You can use the serializeData() function from this article...

$scope.submitEditSyncSettingsForm = function () {
    $http({
        url: "data/postSyncSettings.aspx",
        data: serializeData({ testValue: 'some value' }),
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }).success(function (data) {
        console.log(data)
    }).error(function (err) {
        "ERR", console.log(err)
    })
};

// http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm
function serializeData(data) {
    // If this is not an object, defer to native stringification.
    if (!angular.isObject(data)) {
        return ((data == null) ? "" : data.toString());
    }

    var buffer = [];

    // Serialize each key in the object.
    for (var name in data) {
        if (!data.hasOwnProperty(name)) {
            continue;
        }

        var value = data[name];

        buffer.push(
        encodeURIComponent(name) +
            "=" + encodeURIComponent((value == null) ? "" : value));

    }

    // Serialize the buffer and clean it up for transportation.
    var source = buffer.join("&")
        .replace(/%20/g, "+");

    return (source);
}
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
  • Thanks! This works. I would like to put it in a separate service, which was the case in the article you referred to, but I didn't get it to work. Any ideas how to do that? I am quite new to AngularJS. – peta Oct 23 '14 at 19:29
  • What problems are you having with it? Can you create a jsfiddle or plunker? – Anthony Chu Oct 23 '14 at 19:32
  • I created a new post for this where I pute the current code. Greatful for any help: http://stackoverflow.com/questions/26545033/move-function-to-factory – peta Oct 24 '14 at 09:20
0

1) The data passed on the server should be converted to a URL-encoded string

It can be do it with the following code:

$.param($scope.formData)

2) For form posting you should use the ng-sumbit directive and for validation you can use $invalid/$valid form's property.

$scope.processForm = function() {
        $http({
            method: 'POST',
            url: '...your URL...',
            data: $.param($scope.formData),  // pass in data as strings
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
        })
        .success(function (data) {
            console.log(data);
            if (data.Status == "Success") {
                //...
            } else {
                //...
            }
        });
    };

<form name="myForm" ng-submit="processForm()">
......

<input type="submit" value="Send Text" ng-disabled="myForm.$invalid"> 
Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60