EDIT: I could approach this problem incorrectly. Now im thinking, maybe I should find the button that was pressed, and then get the previous value of the element
Yes, you are right about that. You must take this approach.
I made an example code to use:
HTML:
<div class=verktyg> <form action='sell_items.php' method='POST' id='ajax'> <table class="inventory"> <tr> <td class='verktyg-first-td'>Item 1</td> <td>10</td> <td> <input type='number' name='item_1' value='10'> </td> <td> <button type='submit' class='submit_button'>sell</button> </td> </tr> <tr> <td class='verktyg-first-td'>Item 2</td> <td>20</td> <td> <input type='number' name='item_2' value='20'> </td> <td> <button type='submit' class='submit_button'>sell</button> </td> </tr> </table> </form> </div>
Jquery:
// prevent for submission $("form").submit(function(e) { e.preventDefault(); }); // when submit button is clicked $(".submit_button").on("click", function() { self = $(this); form = self.closest("form"); url = form.attr('action'); type = form.attr('method'); parentTr = self.parent("td").closest("tr"); // get the parent <tr> data = {}; inputElm = parentTr.find("input[type=number]"); // find input element closest to the clicked button name = inputElm.attr('name'); // get input name value = inputElm.val(); // get input val data[name] = value; // send ajax request $.ajax({ url: url, type: type, data: data, success: function(response) { console.log(response); } }); });
So, firstly, I fixed some problems in your code. Similar to how you have the same ID when you made the id='verktyg-first-td' loop. So I changed it to a class.
And I changed the way you activate your function. Instead of starting when you submit the form, run it when you click the button.
But still my amount is undefined. You must determine how to get this value ...
var quantity = $(btn).prev("input[type=number]").val();
Yes, this will work if your structure:
<td> <input type='number' name='item_1' value='10'> <button type='submit' class='submit_button'>sell</button> </td>
But the input element you were looking for is inside another <td> .
So you must first find the nearest <tr>
parentTr = self.parent("td").closest("tr");
then find input[type=number] .
inputElm = parentTr.find("input[type=number]");
Update:
if (isset ($ _ POST ['item'])) Associate Professor detects a button click and says "Undefined index: item"
First, to fix this, add the attributes back to the button element.
eg.
<button type='submit' class='submit_button' name="item" value='button_value'>sell</button>
then add this code below after data[name] = value;
// get button val value = self.val(); name = self.attr('name'); data[name] = value;