Capturing an onClick event when submitting a form

I created a form that collects data to run an external process (bash script) or to create a database query (using queryBuilder). Since both procedures may take some time, I would like to update the submit button as soon as it is pressed , with a message (for example, "Processing ... please wait") or an icon (like animated FontAwesome icons). Here is the function that I installed in my Controller class (Symfony2):

public function inputAction(Request $request)
    {

        $form = $this->createForm(new InputType());
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) 
        {           
            $data = $form->getData();
            $cmd = '... my command using $data and taking some time ... ';
            $process = new Process($cmd);
            $process->setTimeout(120);
            $process->run();

// Alternative DB query
//          $qb = $this->getDoctrine()->getManager()
//              ->createQueryBuilder();
//          $query = $qb->select('COUNT(p)')
//              ->add('from','myBundle:Ec p')
//              ->add('where', 'p.ec LIKE :ec')
//              ->setParameter('ec', $data['..'].'%')
//              ->getQuery();
//              
//          $result = $query->getSingleScalarResult();

            return $this->redirectToRoute('_input');

        }

        return $this->render('myBundle:Default:form.html.twig', array(
            'form' => $form->createView(),
        ));

    }

So I added a jQuery call to my template

{% extends 'myBundle:Default:input.html.twig' %}
{% form_theme form 'bootstrap_3_layout.html.twig' %}

{% block form %}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
{% endblock %}

{% block javascripts %}

{{ parent() }}
<script>
$(function() {
    $('.btn-default').on('click', function() {
    $(this).prepend('<i class="fa fa-refresh fa-spin"></i>  ');
    });
});
</script>

{%endblock %}

. , . "", - , "mouseover" .

1

@Micha, JS :

$(function() {
    $('.btn-default').attr('prepend', 'false')
    $('.btn-default').on('click', function(e) {
    if($('.btn-default').attr('prepend') == 'false'){
        e.preventDefault();
        $('.btn-default').attr('prepend','true');
        $(this).prepend('<i class="fa fa-refresh fa-spin"></i>  ');
        $(this).trigger('click');
    }
    });
});

, DOM ( ), .

+4
2

preventDefault(), submit() click?

<script>
$(function() {
    $('.btn-default').on('click', function(event) {
    event.PreventDefault();
    $(this).prepend('<i class="fa fa-refresh fa-spin"></i>  ');
    $(#my-form).submit();
    });
});
</script>

, .

0

, , -, Safari. ( @Micha @chris-rogers) Chrome Firefox.

0

Source: https://habr.com/ru/post/1616194/


All Articles