Uploading File Images with AJAX and PHP - 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,
....

Related

Image upload via Ajax in PHP[simplest way]

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

File upload fails when using ajax submit with return false

I have a form that has a simple file input.
<form id="uploadFile" name="uploadFile" action="addFile.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="" name="uploadWUID" id="uploadWUID">
<p>Please upload a signed and completed write-up in PDF format. Please file the hardcopy of the write-up per company policy.</p>
<div class="input-group" style="margin-bottom:7px;">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="reportImport" name="reportImport">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
</form>
There is some local javascript that puts the filename in the text input, but the text input is not used in the PHP file.
The uploadWUID is set dynamically and is passed to add the uploaded file to a specific record in a database.
When I submit the form it works just fine. My browser redirects to addFile.php, success is echoed out, the file is moved to the correct directory and the database is updated.
My issues comes when I add return false to my ajax form submission. I get an error back from the php file stating it couldn't find the index when processing $filename = $_FILES['reportImport']['name']; and my upload/database update fails.
$('#uploadFile').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {}
});
return false;
});
Change script code
$('#uploadFile').submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
data: formData,
type: $(this).attr('method'),
url: $(this).attr('action'),
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(response) {
console.log(response);
alert(response);
return false
}
});
return false;
});

jQuery Ajax post file

I try to post an uploaded file via ajax to php.
HTML:
<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data">
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />
JS
$("#uploadForm").submit(function () {
var formData = new FormData();
formData.append( 'csv', $( '#csv' )[0].files[0] );
formData.append( 'name', $( '#name'));
jQuery.ajax({
url: "../lib/import.php",
data: formData,
type: "POST",
success: alert('erfolgreich'),
error: alert('Fehler'),
cache: false,
contentType: false,
mimeType: 'multipart/form-data',
processData: false
});
});
and then i try to get the form data in PHP:
$_FILES['csv']
$_POST['name']
But the Ajax call completes with success and error... I'm confused...
The PHP file will not executed correctly...
Thanks for your help!
You aren't assigning functions to success or error.
You are calling the alert function immediately and then assigning its return value.
You need to create new functions to assign to success and error.
success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },
You are also calling the function as a submit handler, but aren't preventing the normal form submission. Consequently, the browser will load a new page before processing the response to the Ajax request.
$("#uploadForm").submit(function (event) {
event.preventDefault();
Try restructuring your AJAX call with your success and failure code like this:
$.post('../lib/import.php', formData).done(function() {
console.log('done');
}).fail(function() {
console.log('error');
});
See http://api.jquery.com/jquery.post/ for more examples.

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.

Ajax file upload inside modal

I have no idea how to implement this, let me try to explain
I have a form that open inside a bootstrap modal frame in my layout, in this form i have 2 fields
<input type="file" name="photoimg" id="photoimg" value="" />
<input type="hidden" name="consulta" value="5">
I need to submit this to my url with the value 5 for 'consulta' so the script can read and do the proper things with the file,
BUT
I need to do this without refreshing the opened modal, in other words, using ajax to submit the file (for further cropping)
i have this script that do the submit, what i'm doing wrong here?
<script type="text/javascript">
function enviaimagem(){
$.ajax({
type: "POST",
data: { consulta:5 },
dataType: 'html',
url: "<?=JURI::ROOT()?>ajax.html",
//dataType: "html",
success: function(result){
$("#corpo_modal").html('');
$("#corpo_modal").html(result);
},
beforeSend: function(){
$("#corpo_modal").html('');
$("#corpo_modal").css({display:"none"});
$('#ajaxloadergeneric').css({display:"block"});
},
complete: function(msg){
$('#ajaxloadergeneric').css({display:"none"});
$("#corpo_modal").css({display:"block"});
}
});
}
</script>
File upload through AJAX is supported through FormData object:
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
, however it is not supported by all/old browsers( especially IE < 10)

Categories