upload more than 1 image with ajax - php

I wrote script that alows users to submit comment text with image, and I did it with ajax.
yes - upload image with ajax.
I would like to expand this scrpit and alow users to upload more than one file/image. my code don't support that (server side gets only 1 file). can you help me to fix it so I could upload array of files?
HTML:
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
<input type='hidden' name='comment[pageName]' value='yard' class="pagename-field" />
<input type='hidden' name='comment[refID]' value='0' class="refid-field" />
<input type='hidden' name='allowReply' value='1' class="allowReply-field" />
<textarea class="form-control comment-field" name="comment[text]" rows="1" placeholder="כתוב/י תגובה"></textarea>
<input type='file' name='file[]' class='form-control file-field hideBox' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0"/>
<button class="btn btn-primary submit" >SUBMIT</button>
<img src="images/loading.gif" align="absmiddle" class="loader" id="loader">
</form>
JS:
$(function() {
$(document).on('submit','form',function(e) {
e.preventDefault();
var $form = $(this);
var act = 'add';
var file_data = $form.find('.file-field').prop('files')[0];
var form_data = new FormData();
form_data.append('act', act);
form_data.append('comment[text]', $form.find('.comment-field').val());
form_data.append('comment[pageName]', $form.find('.pagename-field').val());
form_data.append('comment[refID]', $form.find('.refid-field').val());
form_data.append('allowReply', $form.find('.allowReply-field').val());
form_data.append('feel', $form.find('.feel-field').val());
form_data.append('file[]', file_data);
$("#loader").show();
// alert(form_data);
$.ajax({
type: "POST",
url: "ajax/addComment.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
success: function(data)
{
$("#loader").hide();
$('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
$("form").reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});

Related

Sending file together with form data via ajax post in php

Here is what I'm trying to do.
I'm uploading a file on the form and send the data via ajax.
Here is my code:
<form enctype="multipart/form-data" name="addcert_form" id="addcert_form" method="post" >
<input type='hidden' id="staffid" name="staffid" value="<?php echo $staffid; ?>" />
<label for="certNumber"><?php echo("Certification Number"); ?></label>
<input type="text" class="form-control certNumber" id="certNumber" name="certNumber" >
<div class="form-group" style="margin-bottom: 0px;margin-left: 15px;">
<label for="file-upload"><?php echo('File Upload'); ?></label>
<input type='hidden' id="file-upload-hidden" name="file-upload-hidden" />
<input type="file" name="file-upload" id="file-upload" accept="application/pdf">
</div>
</form>
$(document).on('change', "#cert-upload", function() {
var ajaxurl = generalObj.ajax_url;
var form = $("#addcert_form");
var params = form.serializeArray();
var formData = new FormData();
var file_data = $('#file-upload').prop('files')[0];
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
formData.append('file-upload', file_data);
$.ajax({
url: ajaxurl + "rzvy_staff_ajax.php",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (res) {
if(res=="file-uploaded"){
swal.fire(generalObj.updated, generalObj.cert-upload_changed, "success");
//location.reload();
}
}
});
});
However, when I see the information, I'm only getting the file info.
I have tried doing $_POST, and $_FILES, however, I'm not getting the information from the form. How can I get all of the information from the form when I upload the file?
Thank you,
Kevin
Here is what I found out. The data was coming over, I should have used both $_FILES and $_POST

Unable to pass a variable through an ajax request

I'am trying to pass a parameter using ajax to another php page and view the passed parameter in there. But its only redirecting page.parameter is not passed
This is my form.Used to get name through input field
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
This is the ajax code I'am using pass my parameter to ajax.php page.
$("#regform").submit(function(e) {
e.preventDefault();
var form = $(this);
//var url = form.attr('action');
var senddata = {"fname": $('#fname').val()};
console.log(senddata);
$.ajax({
type: "post",
contentType: "application/json",
url: "ajax.php",
dataType: 'json',
data: JSON.stringify(senddata),
success: function(data) {
console.log(data);
}
});
Check this.it is working.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
<script>
$("#regform").submit(function(e) {
e.preventDefault();
var senddata = $('#fname').val();
console.log(senddata);
$.ajax({
type: "post",
url: "ajax.php",
dataType: 'json',
data: {fname:senddata},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP
<?php
echo ($_POST['fname']);
?>

send post data input text and file ( php, jquery, ajax) event click

I have one form html then I have 2 input( input text and input file)
my problem input text cannot send post to upload php.
I using jquery ajax to post data
upload.php
<?php
$nama = $_POST['name'];
$filename = $_FILES['file']['name'];
var_dump($nama);
var_dump($filename);
form
<form method='post' action='' enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
Select file : <input type='file' name='file' id='file' class='form-control' ><br/>
<input type='button' class='btn btn-info' value='Upload' id='upload'>
</form>
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
type: "POST",
url: "upload.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Just remove dataType:text. Or you can use dataType:"json" as per your requirement. Well, you can read more on this dataType here also: $.ajax - dataType
And for name parameter, you are missing to append that variable in fd variable.
So, your script should be like this:
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('name',name); // you were missing this, that's why $_POST['name'] was blank
$.ajax({
type: "post",
url: "upload.php",
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Now try by printing below code into your upload.php file:
<?php
echo $nama = $_POST['name'];
echo $filename = $_FILES['file']['name'];
?>

How to pass file object with multiple attribute via jQuery ajax

I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.
HTML:
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
<input type="button" value="Submit" onclick="uploadPhoto();" />
</form>
JS:
var formData = new FormData();
formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('.files-data'), function(i, obj) {
jQuery.each(obj.files, function(j, file){
formData.append('files[' + j + ']', file);
});
});
jQuery.ajax({
url: 'mbAlbumUploader.ajax_url,'
type: 'post',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
alert(response.files);
}
});
PHP function:
function uploadPhoto() {
$fileName_str = '';
foreach($_FILES['photo_upload']['name'] as $f=>$name) {
$extension = pathinfo($name, PATHINFO_EXTENSION);
$fileName_str .= $name . ', ';
}
die(wp_json_encode(array(
'files' => $fileName_str;
)));
}
What I am doing wrong?
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.
HTML
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
JavaScript
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('album_title', jQuery('#album_title').val());
data.append('security', mbAlbumUploader.ajax_nonce);
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('');
});
PHP (upload.php)
You can Access your files from $_FILES global.

upload more than one image with ajax

I wrote script that alows users to submit comment text with image, and I did it with ajax.
yes - upload image with ajax. it's not drag & drop...
I would like to expand this scrpit and alow users to upload more than one file/image. my code don't support that (server side gets only 1 file). can you help me to fix it so I could upload array of files?
HTML:
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
<input type='hidden' name='comment[pageName]' value='yard' class="pagename-field" />
<input type='hidden' name='comment[refID]' value='0' class="refid-field" />
<input type='hidden' name='allowReply' value='1' class="allowReply-field" />
<textarea class="form-control comment-field" name="comment[text]" rows="1" placeholder="כתוב/י תגובה"></textarea>
<input type='file' name='file[]' class='form-control file-field hideBox' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0"/>
<button class="btn btn-primary submit" >SUBMIT</button>
<img src="images/loading.gif" align="absmiddle" class="loader" id="loader">
</form>
JS:
$(function() {
$(document).on('submit','form',function(e) {
e.preventDefault();
var $form = $(this);
var act = 'add';
var file_data = $form.find('.file-field').prop('files')[0];
var form_data = new FormData();
form_data.append('act', act);
form_data.append('comment[text]', $form.find('.comment-field').val());
form_data.append('comment[pageName]', $form.find('.pagename-field').val());
form_data.append('comment[refID]', $form.find('.refid-field').val());
form_data.append('allowReply', $form.find('.allowReply-field').val());
form_data.append('feel', $form.find('.feel-field').val());
form_data.append('file[]', file_data);
$("#loader").show();
// alert(form_data);
$.ajax({
type: "POST",
url: "ajax/addComment.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
success: function(data)
{
$("#loader").hide();
$('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
$("form").reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
You can do it by FormData() object of jQuery. Refer the code below.
HTML:
<input type="file" name="multi_upload[]" multiple />
JQuery:
$(function() {
$(document).on('submit','form',function(e) {
var files = e.target.files;
var data = new FormData();
$.each(files, function (key, value)
{
data.append(key, value);
});
$.ajax({
url: "your-url",
type: 'POST',
data: data,
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR)
{
alert("success");
}
});
});
});
PHP:
$tempfiles = $_FILES;
foreach ($tempfiles as $files) {
$_FILES['multi_upload'] = $files;
move_uploaded_file($_FILES['multi_upload']['tmp_name'],$_FILES['multi_upload']['name']);
}

Categories