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:
Then to call it you would simply do:
and
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.locationdepends 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 themsgas a variable; and rely on the function to provide a string which we set to thewindow.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)