i am new to webdevelopment and atm i am trying to build a function which handels all different buttons on my Page (to call php code by post). It works fine without the switch/case (or if/else) but as soon as i try to dynamically "load" parameters for Post action it does not work properly anymore. It actually works, when i press the button a 2nd time which looks very strange to me :-). The problem is that button_id suddenly shows as "undefined" Could you give me a little advice please?
$(document).ready(function() {
$(".btn").click(function()
{
button_id = $(this).attr("id");
switch ($(this).attr("id"))
{
case "ZXY" :
php_func_name = "ABC"
php_id = "DEF"
break;
case "XYZ" :
php_func_name = "HIJ"
php_id = "KLM"
break;
}
$('#' + button_id).click(function() {
$.post("php_functions.php", {
method: php_func_name,
id: php_id
}, function(data) {
$("#test").html(data);
alert (data);
});
});
});
});
button_id = $(this).attr("id");tovar button_id = $(this).attr("id");. Without the var , it adds button_id to the globalwindowobject so you are actually settingwindow.button_id. It's usually not what you want and can lead to bugs. Consider adding another line after it, to define these vars also:var php_func_name, php_id;. So these variables also remain local and don't get added towindow.