I have to create lot of functions that contain almost same pattern and coding.
Creating multiple function becomes more useful to use different purpose and pages for my project. For example:
function cls(){
$.ajax({
url:"crud/fetch.php",
method:"POST",
data:{cat:'cls'},
success:function(data){
$('#cls').html(data);
}
});
}
function stdt(){
$.ajax({
url:"crud/fetch.php",
method:"POST",
data:{cat:'stdt'},
success:function(data){
$('#stdt').html(data);
}
});
}
function sec(){
......
//same pattern
}
function pdl(){
......
//same pattern
}
I tried to contain these function in one function to reduce code that seems clean, easy for debugging and re-editing.
So I tried storing all desired function name in one array and create function using each index.
But I am getting Uncaught TypeError: cls is not a function. I have tried without using window[cat]. I think it is foolish way, but tried, hoping it can works. Please suggest how can I assign or create function using each array index value.
var menu = ["cls", "stdt", "sec", "pdl", "sub", "xsub", "cls_sub", "cls_xsub", "xam", "mrksch", "grdsch", "sclnfo"];
$.each(menu, function(i,cat){
var ftch = window[cat];
function ftch(){
$.ajax({
url:"crud/fetch.php",
method:"POST",
data:{menu:cat},
success:function(data){
$('#"' + cat+ '"';).html(data);
}
});
}
})
Uncaught TypeError: cls is not a functioncatas parameter and pass the relevant string while calling the function. That would be really clean.