Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

Laravel: Two form with one submit button

I want to submit two form into two url and want to submit from two another functions of a Controller.

<form method="post" url="{ '/url1' }">
</form>

<form method="post" url="{ '/url2' }">
</form>

<button type="submit">Submit</button>

Is it possible to do without AJAX??

Upvotes: 0

Views: 2277

Answers (4)

Ahmet Firat Keler
Ahmet Firat Keler

Reputation: 4021

If you have a main page form and a modal form and you wanna submit both in order, you can do it with javascript like this

    // cause double submits at once
    function doubleSubmit()
    {
        $.post($('#recordPaymentForm').attr("action"), $('#recordPaymentForm').serialize(), function(response) {
            $('#submitEditOrderButton').trigger('click');
        });

        return false;
    }

Leave your main page form as it is and change your modal form on submit attribute like this

<form id="recordPaymentForm" method="POST" action="/orders/{{$order->id}}/payments" onsubmit="return doubleSubmit(event)">

Please not that we first submit modal form and then we trigger on click event of submit button (submitEditOrderButton) on the main page. In this example, we first submit payment form and then we trigger click event of main page form which cause a form submit on the main page.

Upvotes: 0

Eldee
Eldee

Reputation: 58

You could give the forms different ids but same action. Then in the controller called by the submit button, let IF statements check for the form ids and return the respective view desired eg

$requests = $request->all();
    $form_Id = $requests['form1_Id'];

if($form_Id != 'id_of_first_form') {
            return view('url2');
        }else{
           return view('url1');
        }

Upvotes: 0

N69S
N69S

Reputation: 17205

Simple answer : no, without ajax you can't send two requests.

Complicated answer: unless the first one carries the data for both then in the first response, it sends the second request with the data for it. Which is so complicating things, you should just do it in one request.

Upvotes: 2

nomorehere
nomorehere

Reputation: 332

You can use jQuery to submit both forms like in the example below:

  1. First of all, add an id to your button like this

    <button type="submit" id="submitBtn">Submit</button>

  2. Add ID to your forms:

    form method="post" id="form1" url="{ '/url1' }">

    form method="post" id="form2" url="{ '/url2' }">

I don't know what is wrong with the stakoverflow editor, that is why i deleted the "<" sign. 3. Now handle the jQuery click event:

$(document).ready(function(){
  $('#submitBtn').on('click',function(){
     $('#form1').submit();
     $('#form2').submit();

   });

});

Upvotes: 0

Related Questions