Laravel form destination from Javascript

0

I have a form in a blade view, like this:

<form id="delete_form" method="post" action="">
    @method('DELETE')
    @csrf
    <input type="hidden" id="delete_type" name="delete_type" value="">
</form>

The value of action should be something like {{ route('personas.destroy', ['persona'=>$persona]) }}

Up to here, all right. The problem is that the object $persona has to be selected dynamically from javascript, because there are several links that should be able to launch that form, and each one must pass a different $persona object.

I have tried everything that has occurred to me, but the action of the form is not constructed correctly.

How can a form be made in which the object can be changed dynamically in each call?

Thank you.

    
asked by Chefito 24.11.2018 в 13:54
source

1 answer

1

In this case, as it is a dynamic theme, the action should be built "by hand" from javascript in your different events, for example, I'll give you a simple example of how to edit the action attribute of the form, when capturing the event click of two buttons:

$("#borrar1").click(function(){
  $("#delete_form").attr("action","http://tusitio/borrar/"+$(this).data("id"));
  console.log($("#delete_form").attr("action"));
  //una vez editado puedes submitear el form.
  //$("#delete_form").submit();
});

$("#borrar2").click(function(){
  $("#delete_form").attr("action","http://tusitio/borrar/"+$(this).data("id"));
  console.log($("#delete_form").attr("action"));
  //$("#delete_form").submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="delete_form" method="post" action="">
    <input type="hidden" id="delete_type" name="delete_type" value="">
</form>
<button id="borrar1" data-id="1">Test1</button>
<button id="borrar2" data-id="2">Test2</button>

I hope it helps you.

Greetings!

    
answered by 27.11.2018 / 21:52
source