jQuery: Persisting form values before serialize? - javascript

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.

Related

jQuery form.serialize() not giving the current values

I have this function that should submit the serialized values from my form.
Using document.getElementById(form_id) I get the correct form and values, if I serialize this form with data = $(form).serialize(); the values are not correct.
The answers ot other questions suggest the name or the field being disabled being the cause, but that is not the case here.
Here my function with the results form the console.log.
var submit_form = function(form_id){
form = document.getElementById(form_id);
console.log(16, form);
data = $(form).serialize();
console.log(17, data);
url = "/routmeda/checklist/" + form_id
$.post( url, data, function( data ) {storeLogo.reload();} );
}
The checkbox "aanvraagformulier" is unchecked.
Here the output on the console from line 16, correct
And here from line 17, serialize says the checkbox is on, which is the situation when the form was loaded.
How do I get the correct serilization ?
I solved it by destroying the ExtJs window in which the form was displayed, it seems like the close button on this windows didn't do that before.
The document.getElementById(form_id); gave the value of the current window/form while jQuery's selector gave the ghost version of that window/form.
I didn't think it was a ExtJs problem otherwise I would have included that in my question. Thanks for the suggestions.

HTML form with intermediate web service service call before submit

I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).

Build querystring automatically to send form via ajax

I need to send a complete form via ajax to prevent the refresh of the complete page. Since the form has a huge number of inputfields, i dont want to build the querystring manually. I found some scripts collecting all elements in the form and building the querystring automatically. But is there any easier way to build the query string automatically?
using serialize() method of your jquery form wrapper object !
see : http://api.jquery.com/serialize/
http://api.jquery.com/serialize/
http://api.jquery.com/serializearray/
Try jQuery serialize.
Example from jQuery site
$('form').submit(function() {
alert($(this).serialize());
return false;
});
You can use jQuery .serialize to serialize all input fields in the form. Try below script and alert the value,
var formValues = $('form').serialize();
alert(formValues);
you need to have the info in your page and send it in a query string to another page right??
you could simply add the Previous page Type directive in the page you're redirecting to, and add properties in your first page to return the values in the controls and call it using previous page property
refer to this article

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("");
}

Sending a JSON string as a parameter to an action

I have a button on my Ruby on Rails view file.
Firstly when the button is clicked an Ajax call is made which in response gives a JSON string. So far I have accomplished this task.
Here is where I am stuck: The button also redirects me to another action of the same controller. Now I want to send the JSON string received by JavaScript as a parameter to that action.
Is there any way around this?
Your ajax call should look something like this:
... doing stuff before ...
$.ajax(
url:'url-to-script',
success: function(data) {
var json = JSON.parse(data);
$('#hidden-field').val(json); // set a hidden field in your form
$('#from-id').submit();
}
);
$('#submit-button').attr('disabled', 'true'); // disable the button
// set some spinny animation to notify the user that you are waiting.
// time out after a while if you don't get a response
... doing stuff after ...
Basically we fire off the ajax event, disable the button and notify the user you are waiting. When the call returns, your callback method submits the form to rails. You can also set a time out for the ajax call and let the user resubmit if necessary. You can handle the error case however you like.

Categories