简体   繁体   English

多个提交按钮,具有传递变量的不同操作

[英]multiple submit buttons different actions with passing variables

I have a form like the code below (called index.php) with multiple submit buttons. 我有一个像下面的代码(称为index.php)的形式,带有多个提交按钮。 I'd like to have different php actions on submit buttons. 我想对提交按钮进行不同的php操作。 The 1st button without refreshing the browser's page and of course with passing the variables. 第一个按钮,无需刷新浏览器页面,当然也无需传递变量。 The other with normal action which can redirect to a new page (here form_submit.php). 另一个具有正常操作,可以重定向到新页面(此处为form_submit.php)。 I managed to make the 1st button working with the help of this topic but I can't distinguish the 2nd button from the 1st one. 本主题的帮助下,我设法使第一个按钮起作用,但是我无法将第二个按钮与第一个按钮区分开。 Is there any way to switch between functionality of these buttons ? 有什么办法可以在这些按钮的功能之间切换?

<? php>
if($_POST['formSubmit'] == "Next") {
  $var1 = $_POST['name1'];
  $var2 = $_POST['name2'];.
  session_start();
  $_SESSION['variable1'] = $var1;
  $_SESSION['variable2']= $var2;
  header("Location: form_submit.php");
  exit;
}

?>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="name1" id="name1" maxlength="50" value="<?=$var1;?>" />
<input type="text" name="name2" id="name2" maxlength="50" value="<?=$var2;?>" />

<input type="submit" name="dataSubmit" value="Insert Data" />    
<input type="submit" name="formSubmit" value="Next" />

<script>

  $(function () {
    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'data_submit.php',
        data: $('form').serialize(),
      });

    });
  });
</script>
</form>
</body>
</html>

As soon as 1st button doesn't actually need to make submit you can set 'onClick' event handler on it and make it just 'button'. 一旦第一个按钮实际上不需要进行提交,就可以在其上设置“ onClick”事件处理程序并将其设置为“ button”。 In this case only JS will be triggered when you press the button and browser will not submit the form. 在这种情况下,当您按下按钮时,只会触发JS,浏览器不会提交表单。 Here is what I mean: 这是我的意思:

<input type="button" id="justButton" name="dataSubmit" value="Insert Data" />    
<input type="submit" name="formSubmit" value="Next" />

<script>

  $(function () {
    $('#justButton').on('click', function (e) {

      $.ajax({
        type: 'post',
        url: 'data_submit.php',
        data: $('form').serialize(),
      });

    });
  });
</script>

First, add clicked class to button: 首先,将clicked类添加到按钮:

$('.submitButton').click(function(){
    $('.submitButton').removeClass('clicked');
    $(this).addClass('clicked');
});

Than in submit event check button: 比在提交事件检查按钮:

$('form').submit(function(){
    var button = $('.submitButton.clicked');

    if (button.attr('id') == 'name1') {
        ...
    } else {
        ...
    }

    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM