angularjs serialize form data
From the doc:
For a form element's value to be included in the serialized string, the element must have a name attribute.
In your HTML inputs do not have names, hence serialize
returns an empty string. Fix this with something like...
<input type="text" name="keywords" ng-model="keywords" placeholder="enter name...">
<input type="text" name="desc" ng-model="desc" placeholder="enter description...">
And, btw, you don't have to wrap Angular $element
into jQuery function: $element.serialize()
would work ok.
z22
SOreadytohelp Apart from being a full time mobile app developer professionally, I believe in giving it back to the community and StackOverflow provides me this great platform to achieve it. I started with stack few years back when I was a high school student and since then I have been a regular user of stack. I got a chance to communicate with some experts on stack and all my questions were answered in few minutes which otherwise would have taken n number of hours. Not only that but I got an opportunity to solve so many questions of other users. Each upvote that I got was an award for me- I really feel satisfied every time when my answer/question helps others. Thanks a ton stack!
Updated on August 28, 2020Comments
-
z22 over 3 years
i wish to serialize the form data in angularjs. following is the controller code:
function SearchCtrl($scope, $element, $http) { $scope.url = 'php/search.php'; $scope.submit = function() { var elem = angular.element($element); //var dt = $(elem.parent()).serialize(); console.log($(elem.parent()).serialize()); $http({ method: 'POST', url: $scope.url, data: 'first=hgf&last=ghfgh', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function(data, status) { $scope.status = status; $scope.data = data; $scope.result = data; // Show result from server in our <pre></pre> element //var elem = angular.element(e.srcElement); //alert($(elem.parent()).serialize()); }).error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); return false; }; }
edited:
<!DOCTYPE html> <html ng-app> <head> <title>Search form with AngualrJS</title> <script src="../angular-1.0.1.min.js"></script> <script src="http://code.jquery.com/jquery.min.js"></script> <script src="js/search.js"></script> </head> <body> <div> <form ng-controller="SearchCtrl" ng-submit="submit()"> <label>Search:</label> <input type="text" ng-model="keywords" placeholder="enter name..."> <input type="text" ng-model="desc" placeholder="enter description..."> <button type="submit">Search</button> <p>Try for example: "php" or "angularjs" or "asdfg"</p> </form> <pre ng-model="result"> {{result}} </pre> </div> </body> </html>
but nothing gets printed on the console. where am i going wrong?
-
z22 over 11 years$element.serialize() doesnt work alone, it gives me Object [[object HTMLFormElement]] has no method 'serialize' error in chrome console