upload Mutiplos files

Asked

Viewed 46 times

1

How do I get the files on AJAX?

inserir a descrição da imagem aqui

That’s the AJAX that is working, however I am not passing as date the files, I’m taking the PHP

$('#btnenviarpdf').click(function () {

        var id = $('#modalADDPDF').data('id');  

        $.post('estrutura/upaddpdf.php',{acao:'inserir',id:id},function(r) { 

           var m = jQuery.parseJSON(r);        
           if (m.success) {


            $('#modalADDPDF').modal('hide');
            toastr["success"](m.msg);           
            $("#listapdf").load(location.href + " #listapdf>*", "");    

           } else {

            toastr["error"](m.msg);
            $('#modalADDPDF').modal('hide');

           }             
        });
    });

This error occurs:

Notice: Undefined index: img in upaddpdf.php on line 14

PHP:

<?php
    include("../includes/config.php");

    if($_POST){

        $data = array('success' => '0',
                  'msg' => 'Ocorreu um erro, nada foi inserido!');

        $acao   = $_POST['acao'];
        $id     = $_POST['id'];

        IF($acao != ""){
            //INFO IMAGEM
            $file       = $_FILES['img'];  <<<=== linha 14
            $numFile    = count(array_filter($file['name']));

            //PASTA
            $folder     = 'arquivos/anexos';

Now I’ve done it this way, but it’s still the same problem.

JQUERY

$('#btnenviarpdf').click(function () {

    var id = $('#modalADDPDF').data('id');  

    var form_data = new FormData();
    var ins = document.getElementById('multiFiles').files.length;
    for (var x = 0; x < ins; x++) {
        form_data.append("files[]", document.getElementById('multiFiles').files[x]);
    }

    $.post('estrutura/upaddpdf.php',{acao:'inserir',id:id},function(r) { 

       var m = jQuery.parseJSON(r);        
       if (m.success) {


        $('#modalADDPDF').modal('hide');
        toastr["success"](m.msg);           
        $("#listapdf").load(location.href + " #listapdf>*", "");    

       } else {

        toastr["error"](m.msg);
        $('#modalADDPDF').modal('hide');

       }             
    });
});

PHP

<?php
include("../includes/config.php");

if($_POST){

    $data = array('success' => '0',
              'msg' => 'Ocorreu um erro, nada foi inserido!');

    $acao   = $_POST['acao'];
    $id     = $_POST['id'];

    IF($acao != ""){
        //INFO IMAGEM
        $file       = $_FILES['files'];
        $numFile    = count(array_filter($file['name']));

Form:

<form id="formulario" method="post" enctype="multipart/form-data" action="">
                        <input type="hidden" name="acaopdf" value="">
                        <input type="hidden" name="id" value="<?php echo $id?>">
                        <div class="file-field">                    

                            <div class="d-flex justify-content-center">
                                <div class="btn btn-info btn-rounded btn-sm">
                                    <span id="spa">Escolha o arquivo</span>                                         
                                    <input type="file" id="mulitplefileuploader" name="img[]" multiple>

                                </div>

                            </div>
                        <center><input class="btn btn-info btn-rounded btn-sm" id="btnenviarpdf" type="submit" value="Enviar" /></center>
                        </div>

                    </form>
  • Have you tried to var_dump or print_r the $_FILE variable, what was the return? Or try to inspect the request and see if the files are being sent.

  • I already did that, day the variable was not set..

  • I do the editing because it misreads the existing response and does not give details of what the error was, please do as I said, tell me what error occurred using the browser console and look in the network tab (if your browser is in English the tab name is "Network"), if you do not know how to do this view this answer https://answall.com/a/62797/3635

  • thanks for the help, but nothing happens, can be my form

1 answer

0

Your Ajax does nothing but send {acao:'inserir',id:id}, that is there is no way PHP can receive the upload since you have not sent anything, to send the files you need to pass the FormData in the date field and set the processData as false

It will be necessary to pass the action and id on its own FormData:

//O mesmo que acao: 'inserir'
form_data.append("acao", "inserir");

//O mesmo que id: id
form_data.append("id", id);

No JSON.parse required, you can simply use dataType: "json"

Another interesting thing to use is the .fail, because errors may occur on the server or even on the user’s internet, with fail you will be able to inform if something failed in this situation:

.fail(function (xhr, textErr) {
    toastr["error"](textErr);
    $('#modalADDPDF').modal('hide');
});

Should stay like this:

var id = $('#modalADDPDF').data('id');  

var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;

for (var x = 0; x < ins; x++) {
    form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}

//O mesmo que acao: 'inserir'
form_data.append("acao", "inserir");

//O mesmo que id: id
form_data.append("id", id);

$.ajax({
  type: "POST",
  url: 'estrutura/upaddpdf.php',
  data: form_data, //Passa o forma data
  dataType: "json",//Força o tipo json na resposta
  processData: false // <--- false
}).done(function(r) {
   if (m.success) {


    $('#modalADDPDF').modal('hide');
    toastr["success"](m.msg);           
    $("#listapdf").load(location.href + " #listapdf>*", "");    

   } else {

    toastr["error"](m.msg);
    $('#modalADDPDF').modal('hide');

   }     
}).fail(function (xhr, textErr) {
    toastr["error"](textErr);
    $('#modalADDPDF').modal('hide');
});
  • I was editing the duplicates... There are several posts about File + Ajax + PHP - But as you reopened and answered, I’ll leave it to you.

  • @Bacco yes, including one of mine from 2015 that explains this well, only that it has a detail that differs, the field acao: and the countryside id, are not form fields and there is no explanation in the other answer, sorry I kind of go over, but is that I was already in the middle of the answer.

  • There are posts with and without form, and with explanation. The closing for the first one I found was just to avoid someone post duplicate anyway. But as I said, it’s up to you, I can’t pay much attention to it now, anyway. Maybe I don’t have any "complete".

  • There’s no way, I’m going to the refresch of the screen even, I can’t make it work..

  • @Jeffersonmeireles was my mistake, failed to correct the name of the var, the correct is $.ajax({&#xA; type: "POST",&#xA; url: 'estrutura/upaddpdf.php',&#xA; data: form_data,&#xA; dataType: "json",&#xA; processData: false&#xA;}), I just edited the answer, take a look.

  • nothing, I will edit my question and for all the files, I must be missing something

  • @Jeffersonmeireles as so nothing? What error appears in the network tab on the console (F12)? It is still the variable error not defined?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.