How to access data submitted by a form in Angularjs? - javascript

Here is an example from Ng-Book - the Complete Book on Angularjs
Book by Ari Lerner http://jsbin.com/voxirajoru/edit?html,output where ng-form has been used to create nested form elements and perform validation. As the each input field has same value for name attribute so how can on the server side I can access value of all three variables by using some server side language? Let's say it's PHP and method is post. Usually in PHP I would do this:
`$_POST['dynamic_input']`
but how is it possible to access three field values coming from input field using $_POST array?

Using the example from the link you provided, you can access form data by updating the code there with the following.
// Add the fields object as a parameter to submitForm()
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm(fields)" novalidate>
// In the $scope.submitForm() function...
$scope.submitForm = function(data) {
alert(data[0].name); // Alerts name
alert(data[1].name); // Alerts password
alert(data[2].name); // Alerts email
};
If you log out the data received by submitForm(), you get the following:
[{"placeholder":"Username","isRequired":true,"$$hashKey":"004","name":"random name"},{"placeholder":"Password","isRequired":true,"$$hashKey":"005","name":"password"},{"placeholder":"Email (optional)","isRequired":false,"$$hashKey":"006","name":"email#host.com"}]
For passing to your server, package all this up as is or format it to your preference and send it to your server via the built in $http.post() or $resource() inside of the $scope.submitForm function.
An example of the formatted data could be:
$scope.submitForm = function(data) {
var postData = {};
postData.name = data[0].name;
postData.password = data[1].name;
postData.email = data[2].name;
... send postData to server via AJAX ...
// Creates the object: {"name":"random name","password":"password","email":"email#host.com"}
//alert(JSON.stringify(postData));
};

Related

Passing a JavaScript object from my form to my Node app

I have this jQuery code that gets data from my form. I used a console statement to see the value. However I want to pass the data to my Node application so that I can insert into a database.
$(function() {
$('#kiosk_signin').submit(function() {
var data = $('#kiosk_signin :input').serializeArray();
console.log(data[0]);
});
});
Please let me know what I need to do.
Assuming you are using express, posting this to your route.., and inserting into the DB..
You would do something like this in your routes..
router.post('/whereever', function(req,res,next(){
///assuming kiosk_signin is the name of an input field
///and the action is ='/whereever' method='post'
var data = req.body.kiosk_signin
console.log('if you want to log it', data)
db.insert({propert: data}).then(function(){
res.redirect('/home')
})
})
I don't use JQuery for submitting forms if I have a full-stack app, just because I intend on sending it directly to the server. Hopefully that helps..

Is there a way to get the form data that is submitted to the server, before on the client-side javascript?

I have an HTML form
form(method="post)
input(name="field")
button submit
upon submitting it on the server I receive the form data as an object
app.post('/', function(req){
console.log(req.body);
// => {field: 'value'}
});
Is there a way to access this object on the client-side javascript before submitting the form?
form(method="post submit="submit(this)")
function submit(){
this.data? //
// =?> Something that gives the same object
// {field:value}
}
I've searched and found various ways but they only deal with finding the particular fields and elements and extracting the values from them.
document.getElementById("...").value - not what I want.
oText = oForm.elements["text_element_name"]; - not what I want
What I want is the "composed" object that gets sent to the server via POST request.
If you're using jQuery you can use the serializeArray method.
$('#myForm').serializeArray();
Will give you an array like this:
[
{
name: 'inputField1',
value: 'my value'
},
...
]
http://api.jquery.com/serializeArray/

Trying to collect parameters from URL and submit into CRM with form

I have a multi page form.
Page One has a few fields that get passed into the second form, via GET method, and it auto fills the first four fields of the second part of the form.
Page two has a few more questions, and when you submit it, it submits into our CRM(vanillaSoft), and leads to a thank you page.
My current issue:
I want to be able to take an affiliate link, such as:
http://something.com/step-one.html?AFFILIATE_ID=#affid#&SUB_ID=#s1#
I need to dynamically populate the AFFILIATE_ID parameter with a unique transaction ID, and the SUB_ID with a unique ID as well.
I currently have two fields on my first page with hidden fields, ex:
<input type="hidden" name="SUB_ID">
<input type="hidden" name="AFFILIATE_ID">
But that isn't working. I need this date to be sent into the CRM I use.
Any advice?
Thanks!!!
Your current setup will work if you set your form submit method to GET. You probably have it set to POST.
Setting your form method to GET will put those hidden fields in the URL, like you are expecting.
On the last form, set that one to POST (to POST to the server).
You can grab the Query string with JavaScript, like this:
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();​
How can I get query string values in JavaScript?
You could also send both POST and GET methods. But POST can be done only on server side, where JavaScript is Client-side scripting language.
<form method="POST" action="form.php?a=1&b=2&c=3">
PHP -> Send both POST and GET in a form
How to read the post request parameters using javascript

jQuery: Persisting form values before serialize?

I am using jQuery serialize() function to collect data in a form and submit to server using jQuery Ajax "post" method, like this: var params = jQuery('#mainContent form').serialize();.
The strange thing I saw is the serialized data from my form contains old data. It means, all of my changes in form (input to text-field, select on combo-box) is not stored to DOM, so when jQuery call serialize(), it collect the old data which appeared before I change the form. I tried to inspect to each element in that form and call .val(), it still showed the old values.
So how can I persist all my changes to form, that the serialize() method can build the string with newest data I entered?
Here is my snippet code, I called serialize() inside submit handler
jQuery('.myFormDiv input.submit').click(function() {
// Do something
// Collect data in form
var params = jQuery('#mainContent form').serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
Thank you so much.
When are you calling serialize? it should be $('form').submit( [here] ); It sounds like it's being called on page load, before you enter values into the fields, then being used after.
EDIT:
using the submit event instead of on click will catch someone hitting enter in a text field.
jQuery('#mainContent form').submit(function() {
// Collect data in form
var params = jQuery(this).serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
*the above code assume url is define and successHandler is a function.

Manipulate form data before it's sent with jQuery

I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}

Categories