JulianJ JulianJ - 15 days ago 11
jQuery Question

Detecting which button was pressed

I'm trying to detect which was button was pressed with jQuery and then server-side do different things depending on the outcome.

The jQuery works fine (although I may have gone about it in a long- handed way) but I can't figure out why in my code whichever button I press I get the same response from php: "Add button detected". I hope someone can tell me what I've got wrong?

The jQuery

$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;

var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {

$("#results").html(data); //Response


});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;

var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {

$("#results").html(data); //Response

});
});

});


The Php

<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity

if($btn="btn_add"){

echo "<h1>Add button detected</h1>";
//Do stuff

}
elseif($btn="btn_remove"){

echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>


The html Form

<td>
<form id=\ "myForm\" class=\ "myForm\" action=\ "\" method=\ "post\" enctype=\ "multipart/form-data\">
<input type=\ "hidden\" name=\ "user_id\" value=". $collab_userid." />
<input type=\ "hidden\" name=\ "id\" value=".$upload_id." />

<button type=\ "submit\" id=\ "btn_remove\" class=\ "btn_remove\" name=\ "btn_remove\">Remove</button>
<button type=\ "submit\" id=\ "btn_add\" class=\ "btn_add\" name=\ "btn_add\">Approve</button>
</form>
</td>

Answer

You should add the pressed button to your formdata, otherwise the click couldn't be detected.

$(document).ready(function() {
    $(".btn_add").on("click", function() { //If add btn pressed
        var id = this.id;
        var url = "process_ajax4.php?btn=" + this.id;

        var formdata = $('.myForm').serialize();
        formdata += "&btn=btn_add"; // added the btn
        $.post(url, formdata,
            function(data) {

                $("#results").html(data); //Response


            });
    });
    $(".btn_remove").on("click", function() { //If remove btn pressed
        var id = this.id;
        var url = "process_ajax4.php?btn=" + this.id;

        var formdata = $('.myForm').serialize();
        formdata += "&btn=btn_remove"; // added the btn
        $.post(url, formdata,
            function(data) {

                $("#results").html(data); //Response

            });
    });

});