Save photo from user with AJAX and PHP - javascript

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);

Related

Multiple file upload using ajax in wordpress

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.

send image url and data through serialization

I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);

How to upload files using ajax in Codeigniter?

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.

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

How do I add additional POST parameters to ajax file upload?

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,

Categories

Resources