mat_script
mat_script

Reputation: 23

Variable gets "Undefined" in JQUERY Function

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);
        });
    });

}); 
});

Upvotes: 1

Views: 61

Answers (1)

Danilo Körber
Danilo Körber

Reputation: 910

The problem is that you are changing the function for the button.click. As you do not know your HTML code, I would store the php_func_name and php_id data into data- attributes in the button:

<button id="ZXY" class="btn" data-funcname="ABC" data-id="DEF"></button>
<button id="XYZ" class="btn" data-funcname="HIJ" data-id="KLM"></button>
$(document).ready(function() {
    $('.btn').click(function() {
        $.post("php_functions.php", {
            method: $(this).data('funcname'),
            id: $(this).data('id')
        }, function(data) {
            $("#test").html(data);
            alert (data);
        });
    });
}

Upvotes: 1

Related Questions