Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more effective way to serialize a form with angularjs?

Is there a way to serialize function for angularjs?

my post looks like this right now.

$scope.signup_submit = function () {
  var formData = {
    username: $scope.username,
    full_name: $scope.full_name,
    email: $scope.email,
    password: $scope.password,
    confirm_password: $scope.confirm_password
  }

  $http({
    method: "POST",
    url: '/signup',
    data: formData,
  }).success(function (data) {
    if (data.status == 'success') {
      alert('all okay');
    } else {
      alert(data.msg)
    }
  });
}
like image 382
Web Student Avatar asked Apr 08 '13 10:04

Web Student


People also ask

How do you serialize data in a form?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.

What is form serialize JavaScript?

The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

How do you serialize data in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .


Video Answer


1 Answers

This isn't how you should access form data using AngularJS. The data in your form should be bound within the scope.

So use an object, e.g. $scope.formData, which will contain all your data structure, then each of your form elements should be bound to this using ng-model.

e.g:

http://jsfiddle.net/rd13/AvGKj/13/

<form ng-controller="MyCtrl" ng-submit="submit()">
    <input type="text" name="name" ng-model="formData.name">
    <input type="text" name="address" ng-model="formData.address">
    <input type="submit" value="Submit Form">
</form>

function MyCtrl($scope) {
    $scope.formData = {};

    $scope.submit = function() {   
        console.log(this.formData);
    };
}

When the above form is submitted $scope.formData will contain an object of your form which can then be passed in your AJAX request. e.g:

Object {name: "stu", address: "england"} 

To answer your question, there is no better method to "serialize" a forms data using AngularJS.

You could however use jQuery: $element.serialize(), but if you want to use Angular properly then go with the above method.

like image 198
StuR Avatar answered Oct 13 '22 11:10

StuR