0
votes

I need to have two submit buttons that are placed outside my form. Typical solution for two or more submit buttons is either to give each a unique name or same name and a unique value and then check it in $_POST.

Unfortunately, this does not work when I place my buttons outside of form. I've tried to hook up inputs with form's id as "form" attribute and tried to create label with attribute for="input-id" with no luck.

Whichever button I press it is always the first's button name in $_POST.

For example, this is the form:

<form id="my-form" action="some/action">
    <input name="title" type="text">
    <button hidden type="submit" name="submit-form" id="save" value="save">Save</button>
    <button hidden type="submit" name="submit-form" id="save-exit" value="save-exit">Save and Exit</button>
</form>

<label for="save">Save</label>
<label for="save-exit">Save and Exit</label>
1
Why should you place them outside of the form tag? - AgeDeO
What's the issue exactly? What are you trying to achieve? - the.salman.a
I need to place them outside because of my wicked layout that requires those buttons in the header. - be well
Have you tried a JQuery solution? - James
'I've tried to hook up inputs with form's id as "form" attribute' Can you show this attempt? - Patrick Q

1 Answers

0
votes

So in the head of your HTML you need to include this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Then your form would need to have an ID like this with the two buttons having the same class. Importantly you will note the buttons have different IDs.

<form action="" id="form1" method="post">
<input type="text" name="example" required>
<input type="text" name="example" required>
</form>
<button class="submit" id="option1">Submit option 1</button>
<button class="submit" id="option2">Submit option 2</button>

Then the JQuery with AJAX method. To begin with we use the class of the button (in this case submit) to detect a click, at which point it takes the ID of the button. You can then set the action variable to what you wish for each button. We then gather all the form data using the serialize function and send it.

I have not had a chance to test this and had to very quickly mock it up so please let me know of any issues.

$(".submit").on("click", function(){
    var id = $(this).attr("id");
  if(id=="option1"){
  var action = 'action1.php';
  }
  else if(id=="option2"){
  var action ='action2.php';
  }
  data = $("#form1").serialize();
  $.ajax({
    url: action,
    method: 'post',
    data: data
  });
});