Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
form data upload multiple files through ajax together with text fields

Good day all,

I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.

The following is the javascript code submitting the form data.

$(".update").click(function(){

        $.ajax({
        url: 'post_reply.php',
        type: 'POST',
        contentType:false,
        processData: false,
        data: function(){
            var data = new FormData();
            data.append('image',$('#picture').get(0).files[0]);
            data.append('body' , $('#body').val());
            data.append('uid', $('#uid').val());
            return data;
        }(),
            success: function(result) {
            alert(result);
            },
        error: function(xhr, result, errorThrown){
            alert('Request failed.');
        }
        });
        $('#picture').val('');
$('#body').val('');
});

And, the following is the actual form:

<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update  />

This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?

Any help would be greatly appreciated.

Thanks!

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here is ajax, html and php global you can access. Let me know if it works for you.

// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

// Full Ajax request
$(".update").click(function(e) {
    // Stops the form from reloading
    e.preventDefault();

        $.ajax({
        url: 'post_reply.php',
        type: 'POST',
        contentType:false,
        processData: false,
        data: function(){
            var data = new FormData();
            jQuery.each(jQuery('#file')[0].files, function(i, file) {
                data.append('file-'+i, file);
            });
            data.append('body' , $('#body').val());
            data.append('uid', $('#uid').val());
            return data;
        }(),
            success: function(result) {
            alert(result);
            },
        error: function(xhr, result, errorThrown){
            alert('Request failed.');
        }
        });
        $('#picture').val('');
$('#body').val('');
});

Updated HTML:

<form enctype="multipart/form-data" method="post">
  <input id="file" name="file[]" type="file"  multiple/>
  <input class="update" type="submit" />
</form>

Now, in PHP, you should be able to access your files:

// i.e.    
$_FILES['file-0']
about 4 years ago · Santiago Trujillo Denunciar

0

Here's another way.

Assuming your HTML is like this:

<form id="theform">
    <textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
    <!-- note the use of [] and multiple -->
    <input type="file" name="image[]" id="picture" multiple>
    <input name="update" value="Send" type="submit" class="update" id="update">
</form>

You could simply do

$("#theform").submit(function(e){
    // prevent the form from submitting
    e.preventDefault();
    $.ajax({
        url: 'post_reply.php',
        type: 'POST',
        contentType:false,
        processData: false,
        // pass the form in the FormData constructor to send all the data inside the form
        data: new FormData(this),
        success: function(result) {
            alert(result);
        },
        error: function(xhr, result, errorThrown){
            alert('Request failed.');
        }
    });
    $('#picture').val('');
    $('#body').val('');
});

Because we used [], you would be accessing the files as an array in the PHP.

<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>

More information:

  • FormData constructor
  • Multiple file input
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda