简体   繁体   中英

How do i convert this jQuery code into jQuery function?

I have some jQuery codes, which is repeated again and again, i would like to reduce the code i am writing that is by converting it into functions. here is the codes i am using.

$('form#save-user button[name="save-user"]').click(function() {
    var formData = 'option=saveuser&'+$('form#save-user').serialize();
    $.ajax({
        type: 'POST',
        url:  'process.php',
        data: formData,
        success: function(msg){
            if(msg === 'empty') {
                alert('Required Values Missing');
            } else if(msg === 'duplicateEmail'){
                alert('Email already exist');
            } else {
                window.location = "index.php?users&option=edit&user_id="+msg+'&msg=success';
            }
        }
    });
});

$('form#save-user button[name="save-user-close"]').click(function() {
    var formData = 'option=saveuser&'+$('form#save-user').serialize();
    $.ajax({
        type: 'POST',
        url:  'process.php',
        data: formData,
        success: function(msg){
            if(msg === 'empty') {
                alert('Required Values Missing');
            } else if(msg === 'duplicateEmail'){
                alert('Email already exist');
            } else {
                window.location = 'index.php?users';
            }
        }
    });
});

$('form#save-user button[name="save-user-new"]').click(function() {
    var formData = 'option=saveuser&'+$('form#save-user').serialize();
    $.ajax({
        type: 'POST',
        url:  'process.php',
        data: formData,
        success: function(msg){
            if(msg === 'empty') {
                alert('Required Values Missing');
            } else if(msg === 'duplicateEmail'){
                alert('Email already exist');
            } else {
                window.location = 'index.php?users&option=create';
            }
        }
    });
});

I would like to know few things,

a) With reference to above code, how do i convert it to function, as the code have very few changes like, selector name and url of window.location.

b) what do i call the code below, is it the function? function on the go? or dynamic function?

$('selector').event(function(){
     //jQuery Code in wake of event being triggered.
});

I would write a small plugin for it:

(function ($) {

jQuery.fn.myClick = function (destination) {
    this.click(function () { 
        var formData = 'option=saveuser&'+$('form#save-user').serialize();
        $.ajax({
            type: 'POST',
            url:  'process.php',
            data: formData,
            success: function(msg){
                if(msg === 'empty') {
                    alert('Required Values Missing');
                } else if(msg === 'duplicateEmail'){
                    alert('Email already exist');
                } else {
                    window.location = destination(msg);
                }
            }
        });
    });
}

}(jQuery));

Then to call it you would simply do:

$('form#save-user button[name="save-user-close"]').myClick(function() {
    return 'index.php?users&option=create';
});

and

$('form#save-user button[name="save-user"]').myClick(function (msg) {
    return "index.php?users&option=edit&user_id="+msg+'&msg=success';
});

You should be able to see where we're going here; we're adding parameters to the small method we've created, where you can specify what changes between each call.

Because in this instance, the window.location depends on the AJAX response (and we don't know the response when we invoke the function!), we can't simply provide a string (or something similar) as the parameter. Instead, we pass a function which we invoke once the AJAX response is received, provided the msg as a variable; and rely on the function to provide a string which we set to the window.location .


As for your second question, you pass an event handler to the jQuery event methods; an event handler will be a function reference (usually a reference to an anonymous function )

a) I would start by taking the changing fields as params:

function doPost(redirectUrl) {
    var formData = 'option=saveuser&'+$('form#save-user').serialize();
    $.ajax({
        type: 'POST',
        url:  'process.php',
        data: formData,
        success: function(msg){
            if(msg === 'empty') {
                alert('Required Values Missing');
            } else if(msg === 'duplicateEmail'){
                alert('Email already exist');
            } else {
                window.location = redirectUrl.indexOf("{0}") >= 0 ? redirectUrl.replace("{0}", msg) : redirectUrl;
            }
        }
    });
}

$('form#save-user button[name="save-user"]').click(function() {
    doPost("index.php?users&option=edit&user_id={0}&msg=success");
});

$('form#save-user button[name="save-user-close"]').click(function() {
    doPost("index.php?users");    
});    

b) I would call it an anonymous eventhandler (function).

This should do it for you :

JQuery :

function saveuser(formData) {
    $.ajax({
        type: 'POST',
        url:  'process.php',
        data: formData,
        success: function(msg){
            if(msg === 'empty') {
                alert('Required Values Missing');
            } else if(msg === 'duplicateEmail'){
                alert('Email already exist');
            } else {
                window.location = "index.php?users&option=...';
            }
        }
    });
}

HTML :

<element onClick="saveuser('the-form-data')"></element>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM