No matter what I do I can't seem to get a file to upload via AJAX to CodeIgniter method. It always throws and never sees an uploaded file.
HTML
<div>
<h1>Upload Your Translation</h1>
</div>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script>
function submitFile(){
var formUrl = "/system_administration/AJAX_upload_translation";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
</script>
PAYLOAD
Request Method:POST
Status Code:200 OK
------WebKitFormBoundaryvkN2BT8ZDxXmKj7Y
Content-Disposition: form-data; name="userfile"; filename="clippy-windows-8-10.jpg"
Content-Type: image/jpeg
function AJAX_upload_translation()
{
if (!isset($_FILES['userfile']['error']) || is_array($_FILES['userfile']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
}
Try this code..
$('#upload').on('click', function() {
var file_data = $('#foto1').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'your_upload_php_file', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
Set form action path and use this for ajax(better not to use onclick function)
$(document).on("submit", ".myForm", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set form action url at your form
type: $(this).attr("method"),//set form method at your form
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Related
I have a form using both text-fields and upload-fields.
<form action="submit" method="post" enctype="multipart/form-data">
<input type="text" name="textfield">
<input type="file" name="file_upload">
<button type="submit">Submit</button>
</form>
How can I pass all the inserted data via ajax and use the data in PhP?
What I currently trying via ajax is:
var fd = new FormData($('form'));
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: {
fd: fd,
action: 'devplus_submit_annex' // a php function
},
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});
The FormData constructor takes an HTMLFormElement as its argument, you passed a jQuery object.
For jQuery.ajax you pass the form data object alone as the data field
If you need to add data outside of the from you can use the append() method.
var fd = new FormData($('form')[0]);
fd.append('action', 'devplus_submit_annex');
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: fd,
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});
Hi i have problem with ajax and formData
var formData = new FormData($('form')[0]);
formData.append('image', $('inputFile')[0].files[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
in PHP i just print_r $_POST and $_FILES and it's empty.
HTML
<form onsubmit="return false;" enctype="multipart/data-form" method="POST">
<input type="file" id="inputFile" />
</form>
UPDATE
Headers are sent, request payload has the content but still $_POST or $_FILES are emptry.
var file_data = $("#inputFile").prop("files")[0];
var formData = new FormData();
formData.append("image", file_data);
$.ajax({
type: 'post',
cache: false,
processData: false,
url: url,
data: ajaxData,
error: function (result) {},
success: function (result) {}
});
You can get this as $_FILES['image'] in php code
When trying to upload an image using AJAX without submitting the form directly and sending a FormData object to server it returns empty $_FILES array. But if I submit the form using <input type="submit"> tag $_FILES array is not empty and recieves the data.
HTML
<form action="core/update.php" method="post" enctype="multipart/form-data" id="profile-photo" name="profile-photo-form">
<input type="file" id="photo-filename" name="avatar" class="edit-show panel photo-upload">
</form>
<button class="save-button" disabled="disabled">Save</button>
JS
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var form = $('#profile-photo')[0];
var formData = new FormData(form);
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
$('.save-button').on('click', function() {
if ($('#photo-filename').val != '') {
$('#profile-photo').submit();
};
}
UPD
Also $('#profile-photo').serialize() returns blank string.
UPD 2
Can it conflict with the other AJAX-requests on the page?
Try this:
Because user may upload multiple files
jQuery.each(jQuery('#photo-filename')[0].files, function(i, file) {
data.append('file-'+i, file);
});
Instead of
formData.append('avatar', $('#photo-filename')[0].files[0]);
Complete Solution:
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var form = $('#profile-photo')[0];
var formData = new FormData(form);
jQuery.each(jQuery('#photo-filename')[0].files, function(i, file) {
formData.append('file-'+i, file);
});
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
Try the following,
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var formData = new FormData(this); // here I am editing
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
If it is only the file you want to send then you can do it as below and no need to attach form here to formdata:
$('#profile-photo').on('submit', function(e) {
e.preventDefault();
var formdata = new FormData();
var fileInput = $('#photo-filename');
//Use Either this
$.each($(fileInput).get(0).files, function (index, value) {
formdata.append('avatar', value);
});
//Or this
$.each($(fileInput).get(0).files, function (index, value) {
formdata.append(value.name, value);
});
//For single file use this
formData.append('avatar', $('#photo-filename')[0].files[0]);
$.ajax({
url: "core/update.php",
data: formData,
type: "POST",
contentType: false,
cache: false,
processData: false
});
console.log(formData);
});
I need to post with jQuery files from a multiform form.
The problem is I don't know how to send each file individually with a foreach loop, so I can get upload success from each file separately.
Here's my function to send each file to PHP:
var fileInput = document.getElementById ("images_upload_new_album");
if ('files' in fileInput) {
//console.log(fileInput.files);
$.each(fileInput.files, function(index, val) {
/* iterate through array or object */
console.log(fileInput.files[index]);
$.ajax({
url: config.site + "admin/photos/upload_test",
type: 'POST',
data: {file: fileInput.files[index].name},
dataType: 'json',
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
beforeSend: function (data) {
console.log("Before send.");
//console.log(data);
}, // AJAX request is about to be sent
complete: function (data) {
console.log("Complete.");
//console.log(data);
}, // AJAX request has completed
success: function(data, textStatus, jqXHR) // AJAX request has completed successfully
{
console.log("success.");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) // AJAX request has completed with errors
{
console.log("error.");
}
});
});
};
And my PHP test function.
public function upload_test()
{
$received = $_FILES;
echo json_encode($received);
}
What I get from console:
File {webkitRelativePath: "", lastModified: 1418160606000, lastModifiedDate: Tue Dec 09 2014 20:30:06 GMT-0100 (Hora padrão dos Açores), name: "100371.jpg", type: "image/jpeg"…}
Before send.
Modal it's opened
success.
[]
Complete.
This is my multiform:
<form action="http://xxxxxxx.dev/admin/photos/upload" id="upload_form" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="images_upload_new_album[]" value="" id="images_upload_new_album" class="hidden_images_upload" style="visibility: hidden; width: 0px; height: 0px" multiple="multiple" accept=".jpg" />
</form>
I solved the problem by recreating the POST loop:
$('#new-album-modal').on('show.bs.modal', function (e) {
// Runs after show modal event is fired
var fileInput = document.getElementById ("images_upload_new_album");
if ('files' in fileInput) {
jQuery.each($('#images_upload_new_album')[0].files, function(i, file) {
var data = new FormData();
data.append('fileinput', file);
$.ajax({
url: config.site + "admin/photos/upload_test",
type: 'POST',
data: data,
dataType: 'json',
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
beforeSend: function (data) {
console.log("Before send.");
//console.log(data);
}, // AJAX request is about to be sent
complete: function (data) {
console.log("Complete.");
//console.log(data);
}, // AJAX request has completed
success: function(data, textStatus, jqXHR) // AJAX request has completed successfully
{
console.log("success.");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) // AJAX request has completed with errors
{
console.log("error.");
}
});
});
};
});
This problem was solved based on this post: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax
I have below html
This form allows you to upload a file to the server.<br>
<div class="imguploadpath" style="width:100%;height:200px;background-color:#CCC;">
<form name="myFormName" id ="myFormId" action="" method="post">
<input type="file" name="img" id = "image_pe">
<br/><br/><br/><br/>
<input id="cmdSubmit" value="Submit" type="submit" class="">
</form>
</div>
I am trying to get the file field values to upload the file in php using below script
jQuery( "#cmdSubmit" ).on( "click", function() {
var file = jQuery('#image_pe').val();
//i have to send file property to php file in jquery ajax
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
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)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
return false;
});
but var file only return some temp path c://fakepath/image.jpg
how do upload in jquery and php, I need to pass the form field in php file, I know value() jquery function is wrong.
what is the correct way to do it ?
for php file upload i was thinking of using this script http://www.tizag.com/phpT/fileupload.php
Try this:
JQuery:
var formdata = new FormData();
jQuery.each($('#image_pe')[0].files, function(i, file) {
formdata.append('image_pe', file);
});
$.ajax({
url: "/my.php",
data : formdata,
dataType : "json",
type : "post",
cache: false,
contentType: false,
processData: false,
success: function(data){
},
failure: function(){
$(this).addClass("error");
}
});
return false;
PHP Code:
$file = $_FILES['image_pe'];
Check this. This is might be very helpful for you
http://malsup.com/jquery/form/#file-upload