Sending multiple files using ajax without using html form - php

Im using single file input field with multiple upload property. I've already tested single file pass like that and it worked. Now I'm trying to
pass files using an array but there is a mistake.
There is no form.
HTML:
<input id="fileInfo" name="userfile[]" type="file" multiple>
JS:
var formData = new FormData();
var files = [];
for(var i = 0; i < length; i++) {
files[i] = $('input', '#fileInfo')[0].files[i];
}
formData.append('userfile', files);
$.ajax({
url: "example.php",
data: formData,
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
success: function(res)
{
console.log("done");
}
});
PHP:
<?php
$length = sizeof($_FILES['userfile']['name']);
json_encode(array($length));
error.log:
PHP Notice: Undefined index: userfile in /path/to/php on line 2, referer: http://localhost/test

Instead of building an array with the files (which is kind of strange to do since the source already is an array), append the files directly to your FormData object:
var formData = new FormData();
// Get all the files so we easily can get the length etc.
// Not necessary, but it will make the code easier to read.
var files = $('input', '#fileInfo')[0].files;
for(var i = 0; i < files.length; i++) {
formData.append('userfile[]', files[i]);
}
$.ajax({
// your ajax call
});
We've also changed 'userfile' to 'userfile[]' which will make it an array that you can loop through in your PHP.

Related

I'm trying to upload multiple images using AJAX and PHP but there is an error

In my form.php
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file_upload[]" id="file_upload" style="display:none;" required multiple accept="images/*" onchange="preview_image()">
</form>
And there is a submit button below.
In my jquery part
$('#submit').on('click', function(e) {
var files = $('#file_upload')[0].files;
var form_data = new FormData();
form_data.append("file_upload",files);
$.ajax({
url:"execute/Script.php?request=submit",
type: "POST",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode == 1){
alert("Success!");
}
}
});
});
And in my script.php
if($_GET['request']=="submit"){
$gallery_G = "";
foreach($_FILES['file_upload']['error'] as $key => $error){
if($error==UPLOAD_ERR_OK){
$tmp_name = $_FILES['file_upload']['tmp_name'][$key];
$PhotoName = $_FILES['file_upload']['name'][$key];
move_uploaded_file($tmp_name,"../img/properties/$name");
$gallery_G = $gallery_G.';'.$PhotoName;
}
}
$sql = mysqli_query($conn,"INSERT INTO property(photos) VALUES('$gallery_G')");
if($sql) {
echo json_encode(array("statusCode"=>1));
}
else{
echo json_encode(array("statusCode"=>2));
}
}
But it returns me this:
Notice: Undefined index: file_upload in G:\Xampp\htdocs\execute\Script.php on line 31
Warning: Invalid argument supplied for foreach() in G:\Xampp\htdocs\execute\Script.php on line 31
{"statusCode":2}
Is there any solution? I need to send those photos using 'append' method. And need to get those photos in 'Script.php' so that I can process or upload them from there.
Try passing the form element to FormData. No need to call the append method afterwards.
var files = $('form')[0];
var form_data = new FormData(files);
By using the append() method, you are putting a [object FileList] in the $_POST array under the file_upload key
If you just want the files from the form, you would need a loop:
var files = $('#file_upload')[0].files;
var form_data = new FormData();
for (var i = 0; i < files.length; i++) {
form_data.append("file_upload[]",files[i]);
}

$_POST is null from ajax req

so I'm trying to upload files via a form sent using AJAX, except $_POST returns an empty array (so does $_FILES) - though I'm not sure why. Here is the top of my form:
HTML - generated from PHP (inside WP function)
$html .= '<form method="post" class="form-horizontal" id="product-slides-form" enctype="multipart/form-data">';
AJAX
//edit product gallery
$('#update-product-gallery').on('click', function()
{
var product_id = $(this).data('id'),
slides_form = $('#product-slides-form'),
slides_form_data = new FormData(slides_form[0]);
//create array of slides
var slides = {},
counter = 0;
$.each(slides_form.find('input'), function(j, v)
{
if ($(this)[0].files) {
$.each($(this)[0].files, function(i, files)
{
slides_form_data.append('slides-'+ counter, files);
counter++;
})
}
});
//add slideshow data
slides_form_data.append('slides', JSON.stringify(slides));
slides_form_data.append('product-id', product_id);
var slides_data = {};
slides_data['product_id'] = product_id;
slides_form_data.forEach(function(val, key)
{
slides_data[key] = val
});
//if I change data: to below test FormData than it works
var test = new FormData();
test.append('me', 1);
$.ajax({
data: slides_data,
dataType: 'text',
type: 'post',
url: PLUGIN_ROOT+ 'admin/inc/scripts/add-product-slides.php',
cache: false,
contentType: false,
processData: false,
success: function(res) {console.log(res)},
error: function(res) {$.fn.showPopup(2, 'Something went wrong. Please try again.', res)}
})
});
and my script just var_dumps $_POST + $_FILES for now
I console.log'd the FormData using this:
// Display the key/value pairs
for (var pair of slides_data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
and it returns the correct data, so I'm really not sure why my script doesn't get the $_POST data? Am I missing something really obvious?
(if more code is needed - comment and I'll add more)
var slides_data = {};
That is not a FormData object. You need to send a FormData object.
You create one here:
slides_form_data = new FormData(slides_form[0]);
Keep using slides_form_data for all your data. Don't create a second variable and ignore all the work you did to populate the first one.

Ajax: add a variable to a formData

I got a jQuery script which sends info about a picture to a php file through a "formData" variable, like this:
url: 'ajax.php',
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){}
As far as I know, here is the part of the script that generates the content of that formData before it is sent:
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
fd.append('file', files[i]);
var status = new createStatusbar(obj);
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}
}
To catch that data in the php file, I just use
$_FILES['file'][...];
What I would like to do is to simultaneously send an additional javascript variable to the php file, along with the formData, that I would be able to catch as
$_POST['picID'];
How would I do that?
Thank you.
PS the additional javascript variable "picID" is defined at the beginning of the root of the js file so, it should normally be accessible from within any function in that file.
You can append as many key => value to the form data.
fd.append('key', value);
Applying to your scenario,
fd.append('picID', value); //where value is the value of picID
I would recommend that you declare the form data variable fd before the for loop begins. This is because only the file data requires the loop. For additional form data, append them outside the loop
Example
function handleUpload(){
var fd = new FormData();
//commence for loop {
// }end for loop
//append extra key => value
fd.append('key', value);
}

Using a dynamic variable in an ajax query

I'm struggling to pass a GET variable into a jquery file.
My code is
function upload(files){ // upload function
var fd = new FormData(); // Create a FormData object
for (var i = 0; i < files.length; i++) { // Loop all files
fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
}
fd.append('nbr_files', i); // The last append is the number of files
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
data: fd, // We send the data string
processData: false,
contentType: false,
success: function(data) {
$('#result').html(data); // Display images thumbnail as result
$('#dock').attr('class', 'dock'); // #dock div with the "dock" class
$('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
},
xhrFields: { //
onprogress: function (e) {
if (e.lengthComputable) {
var pourc = e.loaded / e.total * 100;
$('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
}
}
},
});
I need the 5 in url: 'ajax/tuto-dd-upload-image.php?order=5' to be the vatriable order passed through a url like domain.com/?order=XX
You can use PHP and export the variable:
var orderId = <?php echo json_encode($_GET['order']); ?>;
function upload(files) {
...
url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,
Or you could parse it directly in javascript:
var orderId = self.location.search.match(/order=(\d+)/)[1];
// Then continue like the previous example
Of course you'll probably need some error checking around this, if there's a chance the GET param might ever be missing.
Try with javascript :
function $_GET(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && result[1] || "";
}
and call $_GET(key) function in your $.ajax request.
var order = $_GET('order');
url: 'ajax/tuto-dd-upload-image.php?order='+order,

Send multiple arrays and a string using json from ajax to php and receiving them on php

These are the two arrays which are sent from ajax call to php
var mycol=new Array();
var mycolval=new Array();
var inputs = document.getElementsByTagName("input");
for (var i = 1; i < inputs.length; i++)
{
if($("#"+inputs[i].id).val().length>0)
{
flag=true;
mycol=inputs[i].id;
mycolval=$("#"+inputs[i].id).val();
}
}
And this is the string
var string = $('#search_input').val();
I have tried the following code but it doesn't seem to work.
Please help me come up with solution.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify(mycol:mycol,mycolval:mycolval,string:string),
success: function(response){}
});
Your code syntax is wrong
data: JSON.stringify(mycol:mycol,mycolval:mycolval,string:string),
should be
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
You might want also want to specify the content type since you're sending JSON
contentType: 'application/json',
then you can access you data
$postdata = json_decode(file_get_contents("php://input"), true);
$mycol = $postdata['mycol'];
though I am skeptical you actually want to send json but rather url encoded key value pairs so you can access them via $_POST['mycol'] etc, if so use
data: {mycol:mycol,mycolval:mycolval,string:string},
instead.
Also
$("#"+inputs[i].id).val()
could be simplified into
inputs[i].value

Categories