1

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

}); 
});
1
  • Where did you get the "undefined" value for button_id ? By the way, consider changing this line: button_id = $(this).attr("id"); to var button_id = $(this).attr("id"); . Without the var , it adds button_id to the global window object so you are actually setting window.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 to window. Commented Oct 19, 2019 at 21:35

1 Answer 1

1

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);
        });
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.