I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,
Related
I am trying to upload multiple images from one input field and want to send form-data with images and action via ajax. Below I am sharing my code
jQuery(document).ready(function() {
var ajax_url = 'admin-ajax.php';
// When the Upload button is clicked...
jQuery(document).on('click', '#upload_multiImages', function(e){
e.preventDefault;
var fd = new FormData();
var files_data = jQuery('.files-data'); // The <input type="file" /> field
// Loop through each data and create an array file[] containing our files data.
jQuery.each($(files_data), function(i, obj) {
jQuery.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
// our AJAX identifier
fd.append('action', 'cvf_upload_files');
jQuery.ajax({
type: 'POST',
url: ajax_url,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
jQuery('.upload-response').html(response); // Append Server Response
}
});
});
});
<input name="my_file_upload[]" id="my_file_upload" type="file" multiple="multiple" accept = "image/*" class="files-data form-control multi with-preview" value="Drag and Drop" />
<input name="all_vendor_file" type="hidden" value="<?php //echo implode(',', $vendor_images);?>">
<button type="submit" name="upload" id="upload_multiImages">Upload</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
But in response I am only getting action files are not appending, due to which I am not able to get files data over ajax function.
I want to send uploaded image and uploaded XML to PHP file using one ajax. I used two form data, Is this the correct way to do it.
<input type="file" class="form-control-file" name="fileToUpload" id="uploadFile"/>
<input type="file" name="imageToUpload" id="uploadImg"/>
<input type="submit" id="upload_xml" name="transcriptform" value="Upload File" class="btn btn-info">
Ajax call:
$('#upload_xml').on('click', function() {
var file_data = $('#uploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var img_data = $('#uploadImg').prop(files('files')[0];
var img_form = new FormData();
img_form.append('img', img_data);
$.ajax({
url: "get_old_contents.php",
//dataType: 'script',
//cache: false,
contentType: false,
processData: false,
data: form_data,img_form; //is this correct
type: 'post',
complete: function(response){
$('#res').html('Your files are uploaded successfully!');
}
});
});
Not quite. You need to send a single FormData object in the data property of the $.ajax call. To do that you can use append() to add both files together, like this:
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#uploadFile').prop('files')[0];
var img_data = $('#uploadImg').prop('files')[0];
form_data.append('file', file_data);
form_data.append('img', img_data);
$.ajax({
// ...
data: form_data,
});
});
You can also simplify this if you can change the name attribute of the file inputs, by providing a reference to the <form> element to the constructor of the FormData object:
<input type="file" class="form-control-file" name="file" id="uploadFile"/>
<input type="file" name="img" id="uploadImg"/>
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
// ...
data: form_data,
});
});
Note that in both cases you should be hooking to the submit event of the form element, not click of the button, and using preventDefault() on the event argument of the handler to stop the standard form submission.
Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!
I have a grid and in this list of data shown and every row has a edit action.
So when Edit button press a popup will open and in this i want to update data and upload a image regarding this selected row.
Data is successfully updated but image is not save in folder.
In Code What I did :
In ajax, i serialize all data when form submit but upload file post data is not showing so i am doing this -
var mts = $('#userfile').val();
var formdata = $('form[name=data_popup]').serialize()+'&IMG_URI='+mts;
console.log(formdata);
HTML Code:
<form action="#" method="post" enctype="multipart/form-data" name="data_popup">
<input type="file" name="userfile">
</form>
Jquery Code :
function update_cat(){
var mts = $('#userfile').val();
var formdata = $('form[name=data_popup]').serialize()+'&IMG_URI='+mts;
console.log(formdata);
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_data/',
type: 'post',
data: formdata
}).done(function(data) {
console.log(data);
});
}
Codeigniter Model Code:
$this->load->library('upload');
$config['upload_path'] = "./application/assets/images/logo";
$config['allowed_types'] = "gif|jpg|png|jpeg";
$config['file_name'] = date('dmYHis');
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$data_upload_files = $this->upload->data();
$image = $data_upload_files[file_name];
Use FormData for ajax upload
var formdata = new FormData($('form[name="data_popup"]')[0]);
This should work for you.
HTML
<form action="#" method="post" enctype="multipart/form-data" name="data_popup">
<input type="file" name="userfile" id="userfile">
</form>
JavaScript
function update_cat(){
var formData = new FormData();
var mts = $('#userfile').get(0).files[0];
formData.append('userfile', mts);
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_data/',
method: 'post',
data: formdata,
processData: false,
cache: false,
contentType: false
}).done(function(data) {
console.log(data);
});
}
PHP
<?php
$this->load->library('upload');
$config['upload_path'] = "./application/assets/images/logo";
$config['allowed_types'] = "gif|jpg|png|jpeg";
$config['file_name'] = date('dmYHis');
$this->upload->initialize($config);
$this->upload->do_upload('userfile');
$data_upload_files = $this->upload->data();
$image = $data_upload_files['file_name'];
Note: I didn't do much on the PHP part since I don't have a full understanding of what you want to do with the file.
Also ensure you call the javaScript function somehow.
I have a problem with saving photos with Ajax and PHP.
This is my form in HTML
<form id="form3">
<input id="photo3" name="photo" class="form-control" type="file" id="fileInput3" />
</form>
And this is my JS
data = $("form#form3").serializeArray();
var file = $("#photo3")[0].files[0];
data.push({name: "photo", value: file});
$.ajax({
url: 'registrace.php',
data: data,
complete: function (response) {
alert(response.responseText);
},
error: function () {}
});
And this is PHP
$output = 'users/'.$namernd.'.jpg';
move_uploaded_file($_GET['photo'],$output);
Everything is copied to my database and works, but photo is not saved to my server.
Ok, i found solution. Just change to this:
var formdata = new FormData();
formdata.append('name', $('#name3'));
formdata.append('password', $('#password3'));
formdata.append('city', $('#city3'));
formdata.append('email', $('#email3'));
formdata.append('file', $('#photo3')[0].files[0]);
And
$namernd = uniqid();
$output = 'users/'.$namernd.'.jpg';
move_uploaded_file($_FILES["file"]["tmp_name"],$output);