简体   繁体   中英

multiple submit buttons different actions with passing variables

I have a form like the code below (called index.php) with multiple submit buttons. I'd like to have different php actions on submit buttons. 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). 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'. In this case only JS will be triggered when you press the button and browser will not submit the form. 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:

$('.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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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