How to call 2 Functions at the same time using Twig AJAX Form?

- 1 answer

Ad

I'm using OctoberCMS based on Laravel and Twig.

I'm using a Twig AJAX Form that has 2 buttons. Each call a PHP function, actionOne() and actionTwo().

How do I make the second button call both functions at the same time?

Using multiple data-request on a button doesn't work. And using multiple functions separated by comma in data-request also doesn't work.

Form

{{ form_open() }}

    <button type="button" data-request="actionOne">Action 1</button>
    <button type="button" data-request="actionTwo">Action 1 & 2</button>

    <input type="checkbox" name="queuedOne[]" value="{{ record.one }}" />
    <input type="checkbox" name="queuedTwo[]" value="{{ record.two }}" />

{{ form_close() }}  

Edit: I have corrected the values of data-request and name.

Ad

Answer

Ad

There are a couple of different ways you could accomplish this.

First option, you could create a third PHP method that simply does both of the things that you want to accomplish and then call that instead:

function onActionThree() {
    onActionOne();
    onActionTwo();
}

and

<button data-request="actionThree">Click me for both previous actions</button>

Second option, you could utilize the AJAX Framework JS API to make two separate AJAX requests to actionOne and actionTwo.

<button id="action-three-btn">Click me for both previous actions</button>

<script>
   jQuery(document).ready(function ($) {
       $('#action-three-btn').on('click', function (e) {
           e.preventDefault();
           $(this).request('actionOne');
           $(this).request('actionTwo');
       });
   });
</script>

I'll leave this off with a final comment, please read https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem and http://xyproblem.info/. This vague abstraction of your questions isn't helping anyone actually address your real problem.

Ad
source: stackoverflow.com
Ad