B.B10
B.B10

Reputation: 171

How to get id of submit type button, when button is pressed

I want to print out the id of the button I pressed. The id is set dynamically for each button in a table. This is my HTML code:

    echo '<td><center><input type="submit" id="'.$row['I_ID'].'" class="btn"
name="Add" value ="Add to cart"><center></td><tr>';

And I want to print the id of the button here.

if (isset($_POST['Add'])) {
    $ID = $_GET['id'];
    echo $ID;
    echo '<br/>' . "* The item has been added to your cart.";
}

Upvotes: 6

Views: 80513

Answers (5)

Ivan Pintar
Ivan Pintar

Reputation: 1881

If you do not wish to use a hidden field, you could set your submit button like this:

<button type="submit" name="id" value="value">Submit</button>

Then you can catch it with $_GET['id'].

You can have many buttons of type="submit" with the same name (id), and the value will be the one which was clicked, or the first one, if the form was submitted by pressing enter.

Upvotes: 14

kapantzak
kapantzak

Reputation: 11750

You can grab the id with jquery and send it via ajax call:

$(document).on('click', 'input.btn', function() {
    var this_id = $(this).attr('id');
    ajaxCall(this_id);
});

function ajaxCall(this_id) {
    var data = 'id=' + this_id;

$.ajax({
    url: 'proccess.php',  
    type: "GET",    
    data: data,
    cache: false,
    success: function (html) {
            DO WHAT EVER YOU WANT WITH THE RETURNED html
    }         
});

Your 'proccess.php':

    if (isset($_POST['Add'])) {
        $ID = $_GET['id'];
        echo $ID;
        echo '<br/>' . "* The item has been added to your cart.";
    }

Upvotes: 0

Sudar
Sudar

Reputation: 19992

As others have said, the id attribute is not passed to PHP.

You can use the name attribute instead of id and it will get passed to PHP.

If you have the following HTML

<input type="submit" name="some_name" class="btn" value ="Add to cart">

The you can access it in PHP as

$_POST['some_name'] = "Add to Cart"

Upvotes: 0

aleation
aleation

Reputation: 4844

Use a hidden input field:

<input type="hidden" value=".$row['I_ID']." name="input2"/>

Then access it in the second script through:

$_POST['input2']; // or $_GET['input2'], depending on the method of the form submitting

Upvotes: 2

Steven Moseley
Steven Moseley

Reputation: 16325

The 'id' attribute doesn't submit to PHP, only the 'value' attribute submits.

What you should do is add a hidden input with the name "id", like this:

echo '<td><center><input type="hidden" name="id" value="' . $row['I_ID'] . '" /><input type="submit" id="'.$row['I_ID'].'" class="btn" name="Add" value ="Add to cart"><center></td><tr>';

Upvotes: 4

Related Questions