how can I get the value of a input field using PHP if there are two forms on the page both of POST method

时间:2019-02-25 17:06:19

标签: php html forms

I want to get the value of an <input> field using PHP. There are two forms on my page both of POST method.

<form method="POST">
  <input type="text" name="first">
  <input type="submit" name="submit" value="submit">
</form>

<form method="POST">
  <input type="text" name="second">
  <input type="submit" name="submit1" value="Post">
</form>

How do I get the value of the second input field? Even though if I use $_POST['second'] it shows me an error:

Undefined index: 'second'

1 个答案:

答案 0 :(得分:0)

W3C规范定义输入只能与一种形式相关联。当您需要使用多种形式并且后端必须知道哪些数据以其他形式存在时,这是不良设计的标志。

<form>元素可以包含表等任意元素结构,甚至可以包含整个文档正文内容。您几乎不需要多种形式。

一个常见的用例是使用多个具有相同名称的提交按钮。只有按下的按钮会成为表单数据的一部分。

<form method="post">
  <input type="text" name="text_input">

  <button type="submit" name="action" value="add">submit</button>
  <button type="submit" name="action" value="update">submit</button>
  <button type="submit" name="action" value="delete">submit</button>
</form>

同样,不要这样做,但是,如果您出于某种原因确实要跨多个表单共享字段,则只能通过javascript拦截表单提交事件来完成。当用户禁用脚本时,这将不起作用。

document.querySelectorAll('form').forEach(e => {
  e.addEventListener('submit', function() {
    document.querySelectorAll('.multi-form-input').forEach(e => e.setAttribute('form', this.id));
  })
})
<input class="multi-form-input" name="common_input" type="text">

<form id="form-1" method="post">
  <button type="submit" name="action" value="1">submit</button>
</form>

<form id="form-2" method="post">
  <button type="submit" name="action" value="2">submit</button>
</form>