Upload csv file with ajax, json, php and Mysql

Asked

Viewed 559 times

0

I’m trying to make a import file csv to the MySQL dealing with errors with JSon but I’m not succeeding, even with a basic test I can return the message, always falls in the else of if.

This is the form:

<form method="post" enctype="multipart/form-data" id="frmImportacao">                       
    <input type="file" name="demo_file" class="file-upload-ajax">
</form> 

This is the script:

    $(document).ready(function(){       
    $('.file-upload-ajax').on('change',function(){              
        $(this).after('<span class="temp-message">Enviado...</span>');
        var formdata = new FormData($("#frmImportacao")[0]);
        $.ajax({
            type: "POST",
            url: "ajax/pUploadImportacaoRH.php",
            enctype: 'multipart/form-data',
            data: formdata,
            async: false,
            contentType: false,
            processData: false,
            cache: false,
            success: function(response) {
                if (response.codigo == "1") {
                $("#msgInsert").html('<div class="alert alert-success fade in"><button class="close" data-dismiss="alert">×</button><i class="fa-fw fa fa-times"></i><strong>AVISO!</strong>  ' + response.mensagem + '</div>');                        
                } else {
                    $("#msgInsert").html('<div class="alert alert-danger fade in"><button class="close" data-dismiss="alert">×</button><i class="fa-fw fa fa-times"></i><strong>ATENÇÃO!</strong>  ' + response.mensagem + '</div>');
                }
            }

        });
    });     
});

In php it’s like this:

$retorno = array('codigo' => 1, 'mensagem' => "RETORNO");
echo json_encode($retorno);
exit(); 

But you always give me that error message: inserir a descrição da imagem aqui

  • pUploadImportacaoRH.php is just that one there?

  • Hello @Juliohenrique, I’m trying for now to see if this script returns me the correct message, already have the upload part, but I’m trying to understand this message.

  • right, so put this before echo json_encode. header('Content-Type: application/json');

  • I put it and it has the same message.

  • changes this: (Response.codigo == "1" to that (Response.codigo == 1 . because Voce is comparing string with number

2 answers

1

The problem is that you are comparing a string with a number, so it will never be the same.

change that if (response.codigo == "1") { for that reason if (response.codigo == 1){

since the return is a number and not a string:

$retorno = array('codigo' => 1, 'mensagem' => "RETORNO");

If an error appears in the header you need to set the return type, with this code:

header('Content-Type: application/json');

leaving your code like this:

$retorno = array('codigo' => 1, 'mensagem' => "RETORNO");
header('Content-Type: application/json');
echo json_encode($retorno);
exit(); 
  • Boy, the same thing, the message persists.

  • @adventistapr guy only experiences doing the basics, ajax with type, url and Success, see what the

  • @adventist was?

  • I’m changing, but I’m having a problem, the php script gives me the message that the file can’t be empty, but it’s not empty

  • But how about this mistake, if I asked if there are only those lines in the code and Voce said yes?

  • I changed the script, pretty much everything.

Show 2 more comments

0


The solution to my problem was solved as follows, following a few tips here from the OS, I re-read the form and the form of the submission.

        <form id="uploadForm" action="" method="post" class="form-horizontal">             
           <fieldset>
              <legend>Informe o arquivo</legend>
              <div class="form-group">
                 <label class="col-md-2 control-label">Escolher arquivo</label>
                 <div class="col-md-10">
                    <input name="userImage" type="file" class="btn btn-default" />                      
                 </div>
              </div>
           </fieldset>
           <div id="msgFoto" style="padding-top:10px;"></div>
           <div class="form-actions">
              <div class="row">
                 <div class="col-md-12">                        
                    <button class="btn btn-primary" type="submit"> <i class="fa fa-save"></i> Importar </button>
                 </div>
              </div>
           </div>
        </form>  
$(document).ready(function(e) {
        $("#uploadForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: "ajax/pUploadImportacaoRH.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                dataType: "json",
                success: function(data) {

                    if (data.codigo == "1") {
                        $("#msgInsert").html('×AVISO!' + data.mensagem + '');                          
                    } else {
                        $("#msgInsert").html('×ATENÇÃO! ' + data.mensagem + '');
                    }

                },
                error: function() {
                $("#msgInsert").html('×ATENÇÃO! Ocorreu um erro ao atualizar o arquivo. Contate o suporte técnico.');
                }
            });
        }));
    });
  • @Juliohenrique, your tips were excellent, thank you.

  • closes your question by signaling the answers as useful, and marking the one that was the solution (you can mark yours if you want)

Browser other questions tagged

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