PHP and Javascript - Help in file upload

1

I have on my client's site, which I assumed from another developer, a meeting and event registration section. In this section, I need to implement a PDF file upload field related to the event / meeting to be registered.

I tried to implement based on other sections of the site that had already been developed and have uploaded files as well. But I still could not make that upload work. Here are the code below:

HTML

        <table>
        <tr>
            <td><b>{label_cadadmin_reunioes_unidade}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>                
                <select id="selectUnidade">     
                    <!-- BEGIN BLOCK_UNIDADES -->
                    <option value="{OBJ->ID}">{OBJ->NOME}</option>
                    <!-- END BLOCK_UNIDADES -->
                </select>
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_tipoinvestidor}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>
                <form>
                    <input type="radio" value="P" name="tipoInvestidor" id="poolOpt">{label_cadadmin_reunioes_poolista}
                    <input type="radio" value="C" name="tipoInvestidor" id="condOpt">{label_cadadmin_reunioes_condomino}
                </form>
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_tipoevento}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td>
                <select id="selectTipoEvento">      
                    <option value="1">{label_cadadmin_reunioes_rcc}</option>
                    <option value="2">{label_cadadmin_reunioes_ago}</option>
                    <option value="4">{label_cadadmin_reunioes_age}</option>
                </select>           
            </td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_datainicial}<span style='color:#E76000'>*</span>:</b>&nbsp;</td>
            <td><input id="dataInicialReuniao" class="dadosInputG" type="text" value=""></td>
        </tr>
        <tr>
            <td><b>{label_cadadmin_reunioes_horainicial}:</b>&nbsp;</td>
            <td><input id="horaInicialReuniao" class="dadosInputG" type="text" value=""></td>
        </tr>
        <tr>
            <td><b>Anexar Arquivo:</b>&nbsp;</td>
            <td>
                <span class="retornodadospessoais">
                <input id="anexoReuniao" type="file" size="30" class="dadosTypeFile" name="anexoReuniao">
                </span>
                <iframe name="upload_iframeReuniao" id="upload_iframeReuniao" style="display:none;"></iframe>

            </td>
        </tr>
    </table>

JAVASCRIPT (with the functions openModalConnectionsEvent and registerNewEvent)

function abrirModalReunioesEventos(){
var close = $('#lblCancelar').val();
var save = $('#lblSalvar').val();
var dialog_buttonsReuniao = {};  

dialog_buttonsReuniao[close] = function(){ 
    $( this ).dialog( "destroy" );
    //window.location = location.href.split("?")[0]+"?menu=reunioesEventos";

    $("#selectUnidade").val($("#selectUnidade  > option:first-child").val());
    $('#poolOpt').removeAttr('checked');
    $('#condOpt').removeAttr('checked');
    $("#selectTipoEvento").val($("#selectTipoEvento  > option:first-child").val());
    $('#dataInicialReuniao').val('');
    $('#horaInicialReuniao').val('');
    $('#anexoReuniao').val('');
};
dialog_buttonsReuniao[save] = function(){
    cadastroNovoEvento();
};

$('#modalCadastraNovaReuniao').attr('title',$('#lblTitleCadastrarReuniao').val());
$('#modalCadastraNovaReuniao').dialog({
    width: 710,
    modal: true,
    autoOpen: false,
    resizable: false,
    closeOnEscape: true,
    position: 'top',
    buttons: dialog_buttonsReuniao,
    close: function(){
    }
});

$('#horaInicialReuniao').mask('99:99');
//definição da lingua dos datepickers
$.ajax({
      cache:false, 
      url: '[:raiz]cadAdmin/getLang',
      dataType: 'json',
      type: 'POST',
      success: function(data) {
            if(data!='eng'){
                var formato="yy/mm/dd"
            }else{
                var formato="dd/mm/yy"
            }
            $( "#dataInicialReuniao" ).datepicker({ 
                dayNamesMin: [$('#lblDom').val(), $('#lblSeg').val(), $('#lblTer').val(), $('#lblQua').val(), $('#lblQui').val(), $('#lblSex').val(), $('#lblSab').val()],  
                monthNames: [$('#lblJan').val(),$('#lblFev').val(),$('#lblMar').val(),$('#lblAbr').val(),$('#lblMai').val(),$('#lblJun').val(),$('#lblJul').val(),$('#lblAgo').val(),$('#lblSet').val(),$('#lblOut').val(),$('#lblNov').val(),$('#lblDez').val()], 
                dateFormat: "dd/mm/yy" //formato
            });
      }
});
$('#modalCadastraNovaReuniao').dialog('open');
}

function cadastroNovoEvento() {
//Pega a data atual
var dataHoje = new Date();
dataHoje.setHours(0); 
dataHoje.setMinutes(0); 
dataHoje.setSeconds(0); 
dataHoje.setMilliseconds(0);    

var ano = ($('#dataInicialReuniao').val()).substr(6,4);
var mes = ($('#dataInicialReuniao').val()).substr(3,2);
var dia = ($('#dataInicialReuniao').val()).substr(0,2);
var dataPrimeiro = new Date(ano,parseInt(mes)-1,dia);
dataPrimeiro.setHours(0); 
dataPrimeiro.setMinutes(0); 
dataPrimeiro.setSeconds(0); 
dataPrimeiro.setMilliseconds(0);

$("#obrigatorio").dialog({
    buttons : {
        Ok : function() {
            $(this).dialog('close');
        }
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

$("#criaEventoDataMaior").dialog({
    buttons : {
        Ok : function() {
            $(this).dialog('close');
        }
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

//Prepara a data para ser inserida em formato de banco
var datainicial = $('#dataInicialReuniao').val();
var substrdataini = datainicial.split('/');
datainicial = substrdataini[2]+'-'+substrdataini[1]+'-'+substrdataini[0]; //AAAA-MM-DD

//Verifica se a data inicial é menor que a data atual
if (($('#dataInicialReuniao').val()).length != 0) {
    if (dataHoje.getTime() > dataPrimeiro.getTime()) {
        $('#criaEventoDataMaior').dialog('open');
        return false;
    }
}

var horainicial = $('#horaInicialReuniao').val();
var substrhorainicial = horainicial.split(':');

if ($("form :radio").is(":checked") == 0) {
    $('#obrigatorio').dialog('open');
    return false;
} else if (($('#dataInicialReuniao').val()).length == 0) {
    $('#obrigatorio').dialog('open');
    return false;
}

$("#envioEventoOk").dialog( {
    buttons : {
        Ok : function() {
            showLoading();
            window.location = location.href.split("?")[0]+"?menu=reunioesEventos";
            $(this).dialog('close');
        } 
    },
    modal : true,
    autoOpen : false,
    resizable : false,
    closeOnEscape : false,
    open : function(event, ui) {
        $(".ui-dialog-titlebar-close").hide();
    }
});

$("#erroExt").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            } 
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        }
    }); 
    $("#envioDocumentoErrorSize").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            }
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            hideLoading();
            $(".ui-dialog-titlebar-close").hide();
        }
    }); 

    $("#envioDocumentoError").dialog( {
        buttons : {
            Ok : function() {
                $(this).dialog('close');
            } 
        },
        modal : true,
        autoOpen : false,
        resizable : false,
        closeOnEscape : false,
        open : function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        }
    });

var ext = $('#anexoReuniao').val().split('.').pop().toLowerCase();
var info = new Array();
info[0] = $('#lblInfoEv0').val();
info[1] = $('#lblInfoEv1').val();
info[2] = $('#lblInfoEv2').val();
info[3] = $('#lblInfoEv3').val();
info[4] = $('#lblInfo0').val();
info[5] = $('#lblInfoEv5').val();
info[6] = $('#lblInfoEv6').val();
info[7] = $('#lblInfoEv7').val();
info[8] = $('#lblInfoEv8').val();
info[9] = $('#lblInfoEv9').val();
info[10] = $('#lblInfoEv10').val();
info[11] = $('#lblInfoEv11').val();
info[12] = $('#lblInfoEv12').val();
info[13] = $('#lblInfoEv13').val();
info[14] = $('#lblInfoEv14').val();
info[15] = $('#lblInfoEv15').val();
info[16] = $('#lblInfoEv16').val();
info[17] = $('#lblInfoEv17').val();

$.ajax({
      async:true,
      cache:false, 
      url: '[:raiz]cadAdmin/cadastraNovoEvento',
      dataType: 'json',
      data: ({
          idunidade: $('#selectUnidade').val(),
          tipoinvestidor: $("input[name='tipoInvestidor']:checked").val(),
          tipoevento: $('#selectTipoEvento').val(),
          datainicial: datainicial,
          horainicial: $('#horaInicialReuniao').val(),
          anexoReuniao: $('#anexoReuniao').val()
      }),
      type: 'POST',
      success: function(data) {
          $("#envioEventoOk").dialog('open');
          $.ajax({
              async:true,
              cache:false, 
              url: '[:raiz]cadAdmin/enviaEmailEvento',
              dataType: 'json',
              data: ({
                  idunidade: $('#selectUnidade').val(),
                  tipoinvestidor: $("input[name='tipoInvestidor']:checked").val(),
                  tipoevento: $('#selectTipoEvento').val(),
                  datainicial: datainicial,
                  horainicial: $('#horaInicialReuniao').val(),
                  info: info
              }),
              type: 'POST',
              success: function(data) { 
              },
              error: function(data) {
              }
          });
      }
});
}

CONTROLLER (function registerNewEvent, called in Javascript)

public function cadastraNovoEvento() {
    //Puxa dados da função cadastroNovoEvento() no js
    $idunidade = $_POST['idunidade'];
    $tipoinvestidor = $_POST['tipoinvestidor'];
    $tipoevento = $_POST['tipoevento'];
    $datainicial = $_POST['datainicial'];
    $horainicial = $_POST['horainicial'];

    // TODO 18/11 - Novo teste de upload de PDF
    $anexo = $_FILES['anexoReuniao']['name']; // TODO Campo novo de cadastro no banco
    $erro = $_FILES['anexoReuniao']['error']; //Detecta erros no upload / Retorna 1 se o tamanho da imagem for maior do que é permitido pelo server
    $size = $_FILES['anexoReuniao']['size'];
    if ($erro != '1' AND $size < 4194304){
        $name = utf8_decode(str_replace("&","",$_FILES['anexoReuniao']['name']));

        $namefile = 'anexosreunioeseeventos/'.$name/*.'.'.$ext*/;

        $file_folder = Config::retorna('application', 'filepath_anexosreunioeseeventos');           

        move_uploaded_file($_FILES['anexoReuniao']['tmp_name'], $file_folder.'/'.$name);

        $name = utf8_encode($name);

        $namefile = 'anexosreunioeseeventos/'.$name/*.'.'.$ext*/;

        CadAdmin::salvaNovoEvento($idunidade, $tipoinvestidor, $tipoevento, $datainicial, $horainicial, $anexo, $namefile/*, $descricao*/);         

        echo '<p>0</p>';
    } else {            
        echo '<p>1</p>';
    }

    echo json_encode(1);
}

MODEL (function SaveNewEvent call on Controller):

public function salvaNovoEvento($idunidade, $tipoinvestidor, $tipoevento, $datainicial, $horainicial, $anexo, $namefile) {      
    //COLOCA NO BANCO
    $id_usuario = Login::retornaIdUser();

    if ($horainicial==''){
        $sql = "INSERT INTO evento(id_unidade, data_ini, tipo_evento, ind_tipo_investidor, id_usuario, caminho_anexo, nome_anexo) VALUES ";
        $sql .= "($idunidade, '$datainicial', $tipoevento, '$tipoinvestidor', $id_usuario, '$namefile', '$anexo')";
    }else {
        $sql = "INSERT INTO evento(id_unidade, data_ini, hora_ini, tipo_evento, ind_tipo_investidor, id_usuario, caminho_anexo, nome_anexo) VALUES ";
        $sql .= "($idunidade, '$datainicial', '$horainicial',  $tipoevento, '$tipoinvestidor', $id_usuario, '$namefile', '$anexo')";
    }
    System::element('db')->query($sql);
}

I believe that some adjustment in the part of Javascript would be missing. Does anyone know what it can be?

    
asked by anonymous 18.11.2015 / 18:00

1 answer

-1

Try this:

In HTML put a form surrounding all its inputs <form id="umaIdQualquer" enctype="multipart/form-data">

And in your javascript add this before ajax

var formData = new FormData($("#umaIdQualquer")[0]);
$.ajax({

In the ajax date field do so: data: formData

$.ajax({
    // .... seu código
    data: formData
    // .... seu código
});

I think this way you can already get the file via $ _FILES.

Just remembering that FormData is part of the html5 API, so it will not work in older versions of browsers.

    
19.11.2015 / 03:51