Image upload via Ajax in PHP[simplest way] - php

I have studied a lot of answers in stackOverflow but haven't figured out the simplest way of uploading an image from a form. I am trying to figure out a way to upload an image using Ajax. Although the form, PHP and Ajax coding is huge, I am giving you the important parts. When I click the submit button, error message is shown, viz undefined index.
HTML
<form method="post" enctype="multipart/form-data">
<tr>
<th>Image</th>
<td><input type="file" name="image" id="img"></td>
</tr>
</form>
Ajax
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
$.ajax({
url:"product_add_back.php",
method:"post",
data:$('form').serialize(),
dataType:"html",
success:function(strMsg){
$("#prod_add").html(strMsg).show().fadeOut(3000);
}
})
})
PHP
$image_name=$_FILES["image"]["name"];
echo $image_name;
die();

$().serialize() will not include $_FILES content, so you need to use FormData object
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
var formdata = new FormData($('form')[0]);
$.ajax({
url: "product_add_back.php",
method: "post",
data: formData,
processData: false,
contentType: false,
success: function(strMsg){}
});
});
Please note that you pass 3 params: data: formData, processData: false and contentType: false

Related

Uploading File Images with AJAX and PHP

I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" class="form-control" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.
this will be undefined because it's inside ajax's scope
Try:
me = this;
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(me),
...
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Why are you wrapping your AJAX call in a
setTimeout(function() {..})
?
By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.
Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added:
var myFormData;
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
myFormData = new FormData(this);
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: myFormData,
....

$_FILES[] is empty in jQuery generated form

I generated the next form in jQuery:
$('.content').append('
<form name="make_new_model_release" enctype="multipart/form-data">
<input data-validate="validate" type="text" name="new_model_release_title" placeholder="Enter new model release title" />
<input type="file" name="newModelReleaseFile" id="newModelReleaseFile" />
<input type="submit" value="Create new model release" />
</form>');
Server side simple:
var_dump($_FILES);
AJAX code:
var data = form.serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: formurl,
data: data,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
after submitting the $_FILES array is empty.
I checked php.ini
file_uploads=On |
upload_max_filesize=128M | post_max_size=128M
Temp folder is allowed for read and write
I tried to make data: new FormData(formId) - nothing changed, $_FILES array is empty.
If you used jQuery('#dailyActivity').serialize(),
It it is not working for <input type'file'>
Have look at this jsFiddle Does not works
and this one .serialize()
Data from file select elements is not serialized.
Have look at this https://stackoverflow.com/a/8758614/3425489
In you case try this
To send <input type'file'> you may want to try this
var formData = new FormData($('form')[0]);
or specify exact data for formdata
var formData = new FormData();
// Append your other Data
formData.append('newModelReleaseFile', $('input[type=file]')[0].files[0]);
And you ajax call will be
$.ajax({
type: 'POST',
url: formurl,
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});

How to upload image through jQuery Steps

I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
Follow this way for upload an image, In this way you don't want HTML form.
Add this code to your mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
Then add this for upload.php
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
$(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);
}
});
}));
$("#upload_doc").on("change", function() {
$("#imageUploadForm").submit();
});
});
</script>
From your comment,
actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.
If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
So your jQuery should be like this:
if(currentIndex == 0){
event.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response) {
console.log(response);
}
});
}
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
$(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);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});

How to get the uploaded image using PHP via AJAX

I need to get the uploaded image using PHP via Ajax
My form fields are,
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="button" id="bidm" name="bidm" value="Next"/>
</form>
In ajax call I have following code :-
$.ajax({
url: './api/addspot.php',
data: $('#rent_details').serialize(),
type: 'POST',
contentType: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
Here I got only spottype value in Ajax success function .But I need to get
all form fields value.
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="submit" id="bidm" name="bidm" value="Next"/>
</form>
$(document).ready(function(){
$("#rent_details").submit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url: "./api/addspot.php",
data: new FormData( this ),
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
});
});
And get by name on your requested page. use $_FILES for upload files.
This will work.
$('#rent_details').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: './api/addspot.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}));
Need to use the FormData() for the ajax data. It took all the form variables and passed it to the ajax. Then in the ajax function, you can retrieve the file name and the temp file name and save the image file to the folder where you required to save.
You need to use the FormData();
Know that this code will not work on IE9 and lower.
This is for multiple file upload.
$(document).on('click', '#bidm', function(e) {
e.preventDefault();
var request = new FormData(this);
var my_files = $(this).closest('form').find('#fileToUpload').files;
$.each(my_files, function(j,file) {
` request.append('fileToUpload['+j+']', file);
});
$.ajax({
url: './api/addspot.php',
data: request,
dataType: "json",
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
Try this to get file field value:
$('input[type=file]').val()
This code is worked

Simple jQuery AJAX file upload

I'm totally noob in jQuery and become desperate to get it to work.
This is the html:
<form method="post" enctype="multipart/form-data">
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
</form>
jQuery:
$("#pic").change(function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'doupload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(dat){
alert('it works maybe');
}
});
});
So I just want to send the file to doupload.php and catch it there with ($_FILES['file']['tmp_name'])
But it's not working (ofc) and I don't find anything which is working either google nor stack...
I use this lilbary: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
You have "type="file"
Change it to type="file"
Also, if you have the ajax sending on change via "$("#pic").change(function() { then you SHOULD NOT have onchange="javascript:this.form.submit();" as well, as it will submit the form while the ajax is still sending, causing possible timing issues (such as the ajax call not completing)
As far as I can tell, you should not have a submit event at all, as the data is already submitted via an ajax call.

Categories