1

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!

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

3 Comments

Actually, it seems to work but with one slight problem. When i choose files from the computer, and then press the submit button...the alert function works yes but still, the browser seems to reload..or displays the loading icon spinning. I want that when the submit button is clicked, that the file is sent to the php file and bring up the alert box. That when i press the browser's refresh button, that it does not ask me if I want to resubmit information. Currently, the browser ask me if i want to resubmit.....how to fix? ..when button is clicked, i dont want browser loading at all.
I've updated my answer, should be ok now. You need to add event param to your function like so: function(e) and use e.preventDefault(); to prevent form from reloading. See updated answer.
@loelsonk I followed your link to save multiple files browed. I chose more than 1 file from my system and alerted a text inside function below: jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file-'+i, file); }); But it alerted only one time. I am able to save the last browsed file only. How can I able to save all the browsed file.
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:

2 Comments

i tested codes. I have a php file that detects when a file or files are being submitted. Here is the issue: when i select 0 files, the php file says that it got a file. When i select 1 file, it says it received a file. And when i select two files, after clicking the submit button, the page just refreshes and form data is cleared. What is the issue?
It's because the button is a type="submit" button within a form -- meaning, by default, if you click on the button it will submit the form and reload the page. You want to prevent that. Check my edit, particularly the HTML and JS code. Notice that I am attaching an onsubmit event handler to the form opposed to onclick event handler to the button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.