John Davidson

php - AJAX Multiple File Upload - Identifying original element?

0 comments
Message:


Assuming multiple upload input types exist on a HTML page, I want to be able to obtain the name attribute of each file upload that is submit with a file, this way the PHP server-side can determine exactly what file uploader is passing what file.


My Code:




$('.php-email-form').submit(function (event) {
event.preventDefault();

var form = $(this);
var data = new FormData();

// add datas of input not file to data object
$.each($(':input', form).not(':input[type=submit]'), function(i, fields){
data.append($(fields).attr('name'), $(fields).val());
console.log($(fields).attr('name'), $(fields).val());
});

// add data from inputs type file
$.each($('input[type=file]', form)[0].files, function (i, file) {
data.append(file.name, file);
console.log(file.name);
console.log($(this).attr('name')); // test, trying to get the name attribute of input type file
});
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="php-email-form" enctype="multipart/form-data">
<input type="text" name="test" value="value"><br>
<input type="file" class="custom-file-input" id="photo" name="photo"><br>
<input type="submit">
</form>


My Answer:
In your code, you are trying to get the name attribute of the file input element using `$(this).attr('name')`, but `$(this)` in this context does not refer to the file input element. You need to store a reference to the file input element before the `$.each` loop and then use that reference to get the name attribute.

Here's an updated version of your code:

javascript
$('.php-email-form').submit(function (event) {
event.preventDefault();

var form = $(this);
var data = new FormData();

// add datas of input not file to data object
$.each($(':input', form).not(':input[type=submit]'), function(i, fields){
data.append($(fields).attr('name'), $(fields).val());
console.log($(fields).attr('name'), $(fields).val());
});

// add data from inputs type file
$('input[type=file]', form).each(function() {
var fileInput = $(this);
$.each(fileInput[0].files, function (i, file) {
data.append(fileInput.attr('name'), file);
console.log(fileInput.attr('name'));
});
});
});


In this updated code, we store a reference to the file input element in the `fileInput` variable before the `$.each` loop, and then use that reference to get the name attribute of the file input element. This way, you can identify which file uploader is passing which file on the server-side.

Rate this post

5 of 5 based on 8147 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us