AJAX Does not enter success: function () when uploading files

0

I have the following code to upload files .csv and I need to show an alert , that is, a answer when I enter the succes , the problem is that it never enters the function.

$.ajax({       
        data: data,  
        type: "POST",     
        dataType: "json",
        url: "class/query/q_addcargue.php",
        processData: false, 
        cache:false,
        contentType: false,
        success: function (data){
            alert("correcto");
        }
    });

I have sometimes used AJAX and I think the problem is for these three lines of code:

    processData: false, 
    cache:false,
    contentType: false,

However, putting them in true or removing them does not help he sent the file in AJAX .

    
asked by Sergio Urbina 15.02.2017 в 21:55
source

3 answers

1

Here is an example of how I do it:

var params = form2js($('#user_form')); //Esta funcion es una modificacion que por dentro trae un serialize form
    params['pg'] = 'GuardaUsuario';

    var data = new FormData();
    $.each($('#file_imagen')[0].files, function (i, file) {
        data.append('filedata', file);
    });

    for (var key in params) {
        data.append(key, params[key]);
    }

    $.ajax({
        type: "POST",
        url: UsuarioHandler, //Este es un url de donde llegara la peticion ej. UsuarioHandler.aspx o Usuarios en caso de usar MVC
        cache: false,
        data: data,
        contentType: false,
        processData: false,
        success: function (response) {
            //Guardado!
        },
        error: function () {
            //error!!!
        }
    });

The issue is that you have to create a FormData first so you can send files and other parameters.

    
answered by 16.06.2017 в 18:40
0

First of all, use var data = $('form').serialize(); does not work with files, that method only works with text type data you should use FormData and the form must have the attribute enctype="multipart/form-data" defined. In order to upload the file using jQuery through AJAX, the following is an example of how to do it:

<form action="class/query/q_addcargue.php" method="POST" enctype="multipart/form-data">
    <input type="file" required />
</form>

<script>
$('form').submit(function(evento) {
    evento.preventDefault(); // Evitar que se recargue la pagina
    var data = new FormData(evento.target); // Datos a partir del formulario
    var $form = $(evento.target) // formulario, es buena practica asignar los selectores de jQuery a una variable cuyo nombre comience con $
    $.ajax({
        url: $form.prop('action'),
        method: $form.prop('method'),
        data: data,
        cache: false,
        contentType: false, // Evita que jQuery defina el encabezado de la petición como 'Content-Type: application/x-www-form-urlencoded'
        processData: false // Evita que jQuery modifique los datos a enviar
    })
    .done(function(response) {
       alert('Éxito'); // No ocurrió un error
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.error(textStatus, errorThrown); // Algo fallo
    });
});
</script>

This method has the disadvantage of not working with old browsers, you can review link to see compatibility

    
answered by 16.02.2017 в 00:26
-3

I have something similar in my project with some variants

$.ajax({
        type: "POST",
        url: "class/query/q_addcargue.php",
        contentType: false,
        processData: false,
        data: data,
        success: function (data) {
            alert("correcto");
        }
    });

removing the dataType: "json" property to define what it will be for multi-part

    
answered by 15.02.2017 в 23:19