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("");
}
Related
I have a form on form-window, and inside form window I have a form with many fields and one upload button. When try to submit form using Ajax.request I have got textfield value but can not get file data. Except filename.
var fd = Ext.getCmp('users-form').form;
var fileInput = document.getElementById('company_logo');
console.log(fd.getEl().dom.files);
params = {
name : fd.findField('name').getValue(),
login : fd.findField('login').getValue(),
email : fd.findField('email').getValue(),
password : fd.findField('password').getValue(),
password_repeat : fd.findField('password_repeat').getValue(),
id : fd.findField('id').getValue()
company_logo : fd.findField('logo').getValue()
}
console.log(params);
Ext.Ajax.request({
url: Scada.reqUrl('users', 'save'),
method: 'post',
params: {
data: Ext.encode(params)
},
success: function() {
console.log('in success');
},
failure: function() {
console.log('in failure');
}
});
Here logo is input type file. I want to send logo data with ajax request. Please help me to figure out the problem. Thanks
Not sure why you started a new question instead of editing Encode form data while fileupload true in Extjs Form Submit as this seems to be the same problem.
Assuming logo is your file upload field you are trying to get the file data using getValue does not actually return the file content (if you use modern there is a getFiles method which returns the selected file objects).
General problems with your approach:
As I stated in my original answer it is not a good idea to send files in a standard ajax request. In your case those problems are:
If you expect getValue to return file contents, you are potentially encoding binary data into a JSON string. This will maybe work but create a large overhead and as the only available JSON datatype that could handle this content is string your parser would have to guess that property company_logo contains binary data and needs to be somehow converted into some sort of file reference.
You are sending files without metadata, so when just adding the raw content into your JSON string you would not be able to detect the expected file type without testing the file in multiple ways
As far as I know you would not be able to access the file content in classic toolkit at all
Submitting the data as a form: In your original question you explained that you submit the form instead of doing Ajax requests which is generally the preferred way.
When you submit a form that contains a file upload field the form will automatically be submitted as multipart/form-data the raw files are added to the request body with it's original content while preserving metadata collected by the browser.
If you look at https://docs.sencha.com/extjs/7.0.0/modern/Ext.Ajax.html#method-request you would have to set isUpload to true and use the form proeprty instead of params, passing a reference to the parent form.
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));
};
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.
I'm using CakePHP and since several days I try to store a java script variable with the help of ajax (jQuery) in a mysql database.
I'm using the following code to do this:
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
But when I click on the submit button, Ajax will post the whole sourcode of my webpage. =(
What I need is a function to store a java script variable to my database but without reloading the page.
I am grateful for any help =)
You told jQuery to serialise a form element. That is, convert the form element to a text string. In other words, you are telling it to get the form's HTML code and send that to your server.
I don't know (or want to know) what the correct way of sending a form's data by AJAX is, but I do know that you need to actually do something like access the form's fields to get their values.
My js is a bit rusty but try changing:
var formData = $(this).serialize();
To:
var formData = $('#saveForm').serialize();
Or:
var formData = $('#saveForm').val().serialize();
That's assuming you want to serialize and store the html of the whole form.
To pull just a value from the form (I don't think you need serialize) try:
var formData = $('#saveForm #someInputName').val();
Of course changing someInputName to whatever the actual name of the field you want to save is.
The problem could be in data parameter.. $('#saveForm').serialize();
should be ok
For those of you that use the Datatables js plugin, how can I create this example with server side data?
The example uses data that is hardcoded in the HTML.
You would basically do the following:
Serialize the form data (using jquery serialize as the example shows)
Submit said data to your form handling scrip (php etc)
They already provide the jquery serialize code so I won't show that, however the jQuery AJAX function will be needed (at the least):
$.ajax({
type: "POST",
url: "some.php",
data: YOUR-SERIALIZED-DATA-HERE,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
And on your Server side PHP file you just grab the correct form array and parse your values ($_POST).
I had the same problem and didn't want to do an ajax save, so I did this:
var table = $("#mytable").datatable();
$("#myform").submit(function () {
var hiddenArea = $("<div></div").hide().appendTo("#myform");
table.$('input:hidden').detach().appendTo(hiddenArea);
// Prevent original submit and resubmit, so the newly added controls are
// taken into account
this.submit();
return false;
});
The idea is that I take all the inputs that are currently not in the dom and move them inside a hidden container.