开发者

Manipulate form data before it's sent with jQuery

开发者 https://www.devze.com 2023-03-21 22:48 出处:网络
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 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&开发者_如何学Camp;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(""); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消