I have a form with several input fields including file inputs.I am using jquery validate plugin.I need to submit the form using ajax.
HTML:
<form method="post" name="addstudent" id="registrationform" enctype="multipart/form-data">
some fields
<input type="submit" id="buttontext"
class="student_registrationform_button" value="submit" />
Jquery:
$('#buttontext').click(function(){
$("#registrationform").validate({
invalidHandler: function(event, validator) {
//some code
},
submitHandler: function(form){
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = $(".file").length, img, reader, file;
$('.file').each(function() { var file = this.files[0];
if (window.FileReader) {
reader = new FileReader();
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
});
$.ajax({
url: "process.php",
type: 'POST',
//data: $(this).serialize(),
data: formdata,
cache: false,
contentType: false,
processData: false,
success:function(data){ //alert(data);
console.log(data);return false;
}
Process.php
When I check echo 'action:'.var_dump($_POST); ,its showing null string
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
var form_data = new FormData(this[0]);
$.each($(obj).find('input[type="file[]"]'), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
form_data.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
form_data.append(val.name, val.value);
});
return form_data;
};
})(jQuery);
var form_id = $('#registrationform');
$.ajax({
type: "POST",
url: "process.php",
data: form_id.serializefiles(),
cache: false,
processData: false,
contentType: false,
success: function (response) {
console.log(data);return false;
}
});
Try this simple function:
submitHandler: function(form){
formdata = new FormData(form);
$.ajax({
url: "process.php",
type: 'POST',
//data: $(this).serialize(),
data: formdata,
cache: false,
contentType: false,
processData: false,
success:function(data){ //alert(data);
console.log(data);return false;
}
Related
I am trying to upload file through jquery formdata without any form. My problem is that it is not sending any data to php file.
Here is my jquery code
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture').prop('files')[0];
var form_data = new FormData();
form_data.append('e_picture', file_data);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
Html
<input type="file" class="form-control" name='e_picture' id='e_picture'>
You are sending the form_data in wrong way
instead of
data: {
form_data
},
just send it like
data: form_data,
jQuery(document).ready(function() {
jQuery('#e_picture').change(function() {
var file_data = jQuery('#e_picture')[0].files;
var form_data = new FormData();
form_data.append("e_picture[]", file_data[0]);
form_data.append('e_uid', '3585');
//});
// data: {e_uid: e_uid, e_picture:'23'},
jQuery.ajax({
url: "index.php?option=com_objectified&task=course_reg.addPicture",
type: 'POST',
data: {
form_data
},
processData: false,
contentType: false,
success: function(result) {
alert('This is ' + result); // Here I show onlu e_uid but it alerts blank result
}
});
});
});
ange content type to :
contentType: 'multipart/form-data',
<input type='file' name='inputfile' id='inputfile'>
I'm trying to upload an image without a form submitting - just after input file is changed:
$('#inputfile').change(function(){
$.ajax({
url: "pro-img-disk.php",
type: "POST",
data: new FormData('#inpufile'),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
});
PHP
$src = $_FILES['inputfile']['tmp_name'];
$targ = "../images/".$_FILES['inputfile']['name'];
move_uploaded_file($src, $targ);
Error:
Undefined index: inputfile...
Any help?
See to the following changes:
<input type='file' name='inputfile' id='inputfile'>
Here's how you should have sent the ajax request:
$(document).ready(function() {
$('#inputfile').change(function(){
var file_data = $('#inputfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "pro-img-disk.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
});
});
And lastly, here's how you should have processed the form data:
$src = $_FILES['file']['tmp_name'];
$targ = "../images/".$_FILES['file']['name'];
move_uploaded_file($src, $targ);
Try this:
var file_data = $('#inputfile').prop('files')[0];
var form_data = new FormData(); // Create a form
form_data.append('inputfile', file_data); // append file to form
$.ajax({
url: "pro-img-disk.php",
type : 'post',
cache : false,
contentType : false,
processData : false,
data : form_data,
success : function(response){
alert(response);
}
});
in php you can get the file data like:
$_FILES['inputfile']
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);
});
These is my form
<form action="<?php echo base_url();?> candidate/ajaxadd" name="candidate_form" method="post" id="candidate_form" enctype="multipart/form-data">
These is ajax function in jquery validation plugin
submitHandler: function(form) {
var formData = new FormData($(this)[0]);
$.ajax({
url: form.action,
type: form.method,
data: formData,
async: false,
complete: dispaly_candidate,
success: function(response) { alert(response);
if(response == "false"){
alert("Please enter all fields");
}
},
cache: false,
contentType: false,
processData: false
});
I don't understand question but:
submitHandler = function(form) {
var formURL = form.attr("action");
var formData = form[0];
var formData = new FormData(formData);
$.ajax({
url: formURL,
type: "POST",
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data) {
var response=$.trim(data);
alert(response);
if(response === "false"){
alert("Please enter all fields");
}
}
});
};
// use finction:
submitHandler($("#candidate_form"));
You need to ask the question in detail. And this function is a correction that (I guess) you're looking for.
Here is my form
<form name="uploadImg" id="uploadImg" class="profile-image" enctype="multipart/form-data">
<input type="file" name="profile" id="updProfileImg">
</form>
Here is my jquery event
$("#updProfileImg:file").change(function() {
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
})
})
But the change event is not triggering form submit so I tried trigger('submit') but the page is refreshing instead of submitting in ajax.
You are binding the events incorrectly. As you currently have it, changing the field will trigger the binding of the submit. It need to be like this:
// bind the submit event
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
});
});
// bind the change event to trigger a submit
$("#updProfileImg:file").change(function() {
$("#uploadImg").submit();
});
A simple modification works
$("#updProfileImg:file").change(function() {
//$('#uploadImg').submit(function() {
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
//})
})
you should try this code:
$("#updProfileImg:file").on("change", function(){
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {},
success: function() {}
})
});
because i expect the ".change()" will be fired one time in the first change.