简体   繁体   中英

How to pass an array of “FormData” via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax

var dataPanier=[];

function addarray(objser)
{
 dataPanier.push(objser);

}


$('.target').click(function() {

  var btn_name=$(this).attr("name");

     switch(btn_name) {

       case 'FormPVC':

       var dataformPVC = new FormData(),
           form_data = $('#'+btn_name).serializeArray();

          $.each(form_data, function (key, input) {
              dataformPVC.append(input.name, input.value);
           });
          dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
           addarray(dataformPVC);
break;
.
.
.
more . . .

I am attempting to send multiple forms data as an array by ajax to a Larave controller.

$.ajax({
    type: 'POST',
    url: 'lsitedevis',
    data: array ,
    success: function(data) {
        toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});

    }
});

As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:

var formData = $('#form1, #form2').serialize();

$.ajax({
    type: 'POST',
    url: 'lsitedevis',
    data: formData ,
    success: function(data) {
        toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
    }
});

You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div> .

 $("#btnTest").click(function(){ var formData = $('#frm1, #frm2').serialize(); console.log(formData); $.ajax({ method: 'POST', url: 'lsitedevis', data: formData , success: function(data) { toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000}); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="frm1"> <input name="n1" type="text"/> <input name="n2" type="hidden" value="test2"/> <input name="n3" type="hidden" value="test3"/> </form> <form id="frm2"> <input name="n1" type="text" /> <input name="n2" type="hidden" value="test2"/> <input name="n3" type="hidden" value="test3"/> </form> <input type="button" id="btnTest" value="send"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM