英文:
How can I get the array index of a button I clicked out of multiple buttons
问题
我有一个购物车表单,通过$_SESSION
迭代列出每个存储的项目的详细信息。该表单包括相同的多个表单控件,包括用于取消的<button>
元素。
我面临的问题是,我无法让PHP识别点击了哪个取消<button>
,因此无法指定要从表单中删除的项目。
表单控件的代码如下:
......
if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
endif;
echo '<button name="cancel[]">Cancel</button>';
......
取消按钮具有数组格式的name
属性,同时运行var_dump
会返回$_SESSION[]
的所有内容。
请帮助我找到识别点击了哪个取消按钮的任何方法。
谢谢阅读。
英文:
I have a form for a shopping cart that lists the details of each stored item by iteration using $_SESSION
. This form consists of same multiple form controls including <button>
elements for cancellation.
The problem I'm faced with is I cannot get PHP to identify which cancellation <button>
was clicked, so I'm unable to specify the item to delete from the form.
The code of the form controls goes:
......
if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
endif;
echo '<button name="cancel[]">Cancel</button>';
......
The cancel button has an name
attribute in array format and also running var_dump
returns all of the content of $_SESSION[]
.
Please help me find any ways to identify which cancel button was clicked.
Thanks for reading this.
答案1
得分: 0
每个HTML按钮元素都可以有一个value属性。只需用您需要的标识符填充它以识别您的取消按钮。
当提交表单时,您可以在您的php脚本中使用 `$_POST['cancel']` 来访问标识符。
只有当按钮用于提交表单时,按钮及其值才会被提交。您必须使用type属性来提交表单。
在使用AJAX时(千万不要使用jQuery!),在按钮上设置事件侦听器时无需使用type属性。只需读取值并将其用作请求的查询参数。
此示例设置了一个事件侦听器,监听点击事件,并异步向`cancel.php`发送带有查询参数的请求,例如 `item=1`。值是从每次点击的按钮的value属性动态确定的,并在PHP脚本中使用 `$_GET['item']` 可供您使用。
所示示例并不好,因为它为每个按钮设置了一个事件侦听器。这可能会导致HTML页面的性能问题,具体取决于按钮的数量。最好的做法是在父表单元素上设置一个单独的事件侦听器,然后用它来确定相应的按钮。所示示例仅供参考。
有关使用JavaScript fetch API 的详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
英文:
Every HTML button element can have a value attribute. Just fill it with the identifier you need to identify your cancel button.
<button name="cancel" value="<?= htmlspecialchars($i) ?>" type="submit">
Cancel
</button>
When submitting the form you can access the identifier with $_POST['cancel']
in your php script.
The button and its value is only submitted if the button was used to submit the form. You have to use the type attribute to submit the form.
When using AJAX (for god 's sake don 't use jQuery!) you don 't have to use the type attribute when setting an event listener on the button. Just read out the value and use it as query argument for your request.
<button name="cancel" value="<?= htmlspecialchars($i) ?>">
Cancel
</button>
<script>
let buttons = document.querySelectorAll('button[name="cancel"]');
buttons.forEach(button => {
button.addEventListener('click', async (event) => {
event.preventDefault();
let value = event.currentTarget.value;
let response = await fetch('cancel.php?item=' + value);
...
});
});
</script>
The example sets an event listener that listens on a click event and fires an async request to cancel.php
with the query argument, e.g. ìtem=1
. The value is determined dynamically from the value attribute of the button with each click and is available to you in the PHP script with $_GET['item']
.
The example shown is not good because it sets an event listener for each button. This can lead to performance problems of the HTML page depending on the number of buttons. It would be better if a single event listener is set on the parent form element, which is then used to determine the respective buttons. The example shown is only intended as an illustration.
For details using the JavaScript fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
答案2
得分: 0
以下是您要翻译的部分:
首先,您必须为每一行分配一个唯一的ID或值。下面的示例可能会有所帮助。
我在这里所做的是,我只是向button
标签添加了一个名为data-target
的新自定义属性。除此之外,我还添加了一个自定义类actionBtn
来在JS中识别所有这些按钮。
......
if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
endif;
// 你可以更改数组元素,使用每行的唯一ID或唯一值,而不是`$_SESSION[$i]['stocks']`
echo '<button class="actionBtn" name="cancel[]" data-target="'.$_SESSION[$i]['stocks'].'">Cancel</button>';
......
在此之后,我创建了一个JS事件,当这些按钮被点击时触发JS函数。我假设您的项目中使用了jQuery。
<script>
$(function(){
$('.actionBtn').on('click',function(event){
// 取消按钮点击时的所有默认操作。
event.preventDefault();
// 为了让你理解,我们创建了一个变量,用于存储需要从`$_SESSION`中移除的值。
var target_to_remove = $(this).attr('data-target');
// 现在我通过AJAX调用将值发送到服务器。
$.post('<some_destination_url>.php',{target : target_to_remove},function(response){
/* ... 从服务器接收响应后在此执行必要的操作 ... */
if($.trim(response) == 'success')
{
alert('success');
} else {
alert('failed');
}
});
});
});
</script>
现在JS部分已经完成,我们必须在PHP脚本中捕获$_POST
数据。
文件: `<some_destination_url>.php
if(isset($_POST['target']))
{
for($i=0;$i<count($_SESSION);$i++)
{
if($_SESSION[$i]['stocks'] == $_POST['target'])
{
/* 如果你想要删除整个父数组,请使用下面的方法 */
//unset($_SESSION[$i]);
/* 如果你只想删除第三级数组元素,请使用下面的方法 */
//unset($_SESSION[$i]['stocks']);
// 最后向JS回显一些内容,以便它知道任务是否成功。
echo 'success';
}
}
// 如果没有找到元素,则输出失败信息。
echo 'item not found';
}
else
{
// 如果`$_POST`未设置,则输出一些内容。
echo 'Invalid attempt to remove array element.';
}
希望这可以帮助您理解并使用这段代码。
英文:
First you have to identify each row with some unique ID/value. Below shown example may help you.
What I have done here is, I have just added a new custom attribute to button
tag called data-target
. Along with this, I have added a custom class actionBtn
to identify all such buttons in JS.
......
if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
endif;
// you can change the array element with unique ID or unique value for each row instead of `$_SESSION[$i]['stocks']`
echo '<button class="actionBtn" name="cancel[]" data-target="'.$_SESSION[$i]['stocks'].'">Cancel</button>';
......
After this, I have created a JS event which triggers a JS function when these buttons clicked. I am assuming you are using jQuery in your project.
<script>
$(function(){
$('.actionBtn').on('click',function(event){
// cancel all default actions when button clicked.
event.preventDefault();
// to make you understand, we are creating a variable which stores the values that needs to be removed from `$_SESSION`
var target_to_remove = $(this).attr('data-target');
// Now I am sending the value to server via AJAX call.
$.post('<some_destination_url>.php',{target : target_to_remove},function(response){
/* ... Do necessary action here after you receive response from server ... */
if($.trim(response) == 'success')
{
alert('success');
} else {
alert('failed');
}
});
});
});
</script>
Now as the JS part is done, We have to capture the $_POST
data in PHP script.
File: <some_destination_url>.php
if(isset($_POST['target']))
{
for($i=0;$i<count($_SESSION);$i++)
{
if($_SESSION[$i]['stocks'] == $_POST['target'])
{
/* if you want to remove whole parent array then use below */
//unset($_SESSION[$i]);
/* if you want to remove 3rd level array element only, then use below */
//unset($_SESSION[$i]['stocks']);
// finally echo something back to JS so that it knows task was successfull or not.
echo 'success';
}
}
// echo failure if no elements found.
echo 'item not found';
}
else
{
// echo something if `$_POST` is not set.
echo 'Invalid attempt to remove array element.';
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论