Sending files with ajax not working as expected - javascript

I have a form which gets files along with other inputs , I want to pass those data to my ajax function. But when i check for those files in server , the server doesn't receive the file. I am new to ajax and Jquery. Here is what i have done.
<form id = "comp_inter_form">
<input type="radio" name="inter_fit" id="inter_good_fit" value = "good" >
<input type="radio" name="inter_fit" id="inter_bad_fit"
<input id="report_upload" type="file"/>
<input id="skype_upload" type="file"/>
<input id="audio_upload" type="file"/>
<input type = "submit" class = "update_interview_btn btn btn-primary" value = "Update"/>
</form>
Ajax function
function completeInterview(id,profile_id){
console.log("Candidate ID is : "+id+"\n Profile id is :"+profile_id );
$('#completeIntModal').modal('show');
var candidate_id = id;
var profile_id = profile_id;
var inter_fit,report_file,skype_file,audio_file;
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
});

Please try to make it like following and check if it works, As you are trying to post content VIA ajax with file input, it has to be treated separately.
You have to use FormData for this.
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
var formData = new FormData();
formData.append("inter_fit",inter_fit);
formData.append("candidate_id",candidate_id);
formData.append("profile_id",profile_id);
var fileInput = $("#report_upload").get(0);
formData.append("report_file",fileInput.files[0]);
fileInput = $("#skype_upload").get(0);
formData.append("skype_file",fileInput.files[0]);
fileInput = $("#audio_upload").get(0);
formData.append("audio_file",fileInput.files[0]);
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
contentType: false, // Not to set any content header
processData: false, // Not to process data
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
On the server side you need to check for posted file array and process those accordingly.

Related

How to post form input values including image file with ajax json stringify

This is my form HTML Code
<form id="PostOfficeFeed" enctype="multipart/form-data">
<input type="text" name="feed_title">
<textarea name="feed_text"></textarea>
<input type="file" name="feed_img" id="FeedImg" />
<button type="submit" id="PostOfficeBtn">Post</button>
</form>
This is my jquery and ajax code
$('#PostOfficeBtn').click(function(){
$("#PostOfficeFeed").validate({
rules:{
feed_title:{required:true, minlength:10},
feed_text:{required:true},
feed_img:{required:false, extension:"jpg|jpeg|png"},
feed_youtube:{required:false},
feed_video_url:{required:false, url: true}
},
messages:{
feed_title:{required:"Feed Title", minlength:"Enter Min 10 characters"},
feed_text:{required:"Feed Description"},
feed_img:{required:"img", extension:"Upload only jpg jpeg png files"},
feed_youtube:{required:"img"},
feed_video_url:{required:"url", url:"Enter Valide URl"}
},
submitHandler:function(){
//Method One
// var formData = $('#PostOfficeFeed')[0];
// console.log(formData);
// var data = new FormData(formData);
// //$("#LoadingMsg").modal("show");
// var JsonDate = JSON.stringify(
// Object.fromEntries(data)
// );
// console.log(JsonDate);
// Method Two
var imgFile = document.getElementById('FeedImg');
var imgfileList = imgFile.files;
if(imgfileList && imgfileList != null && imgfileList.length > 0) {
JsonDate.append(imgfileList[0].name, imgfileList[0].value);
JsonDate.append('feed_img', imgfileList[0].value);
}
var JsonDate = new FormData();
var other_data = $('#PostOfficeFeed :input').serializeArray();
$.each(other_data, function (key, input) {
JsonDate.append(input.name, input.value);
});
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: URL+'post-feeds/test.php',
dataType:"json",
data: JsonDate,
processData: false,
contentType: false,
cache: false,
success: function(data){
if(data.response==="success"){
$("#LoadingMsg").modal("hide");
swal("Successfully", data.message, "success");
$('#PostOfficeFeed')[0].reset();
}
else{
swal("Error", data.message, "error");
}
}
});
return false;
}
});
});
I have tried so much but I dont know where iam missing.
When I am using method one: I can able to post only text input fields not with image
When I am using method two: I can able to upload and post the image only
and Actually Iam looking to get both text input value and image input value
would anyone please help me to correct my code or suggestions
Thank you
In advance for your time and consideration

How to get ID when using new FormData(); javascript/codeigniter

I wasted 3 hours searching for the right syntax. How can i get the value of "prop_id" in javascript.
view -
<input type="hidden" name="prop_id" value="<?=$prop_id_inserted?>">
javascript
function upload_docu_by_type(prop_id, input, filetype) {
var fd = new FormData();
var fileInputs = $("." + input);
$.each(fileInputs, function (i, fileInput) {
if (fileInput.files.length > 0) {
$.each(fileInput.files, function (k, file) {
fd.append('images[]', file);
});
}
});
fd.append("prop_id",input);
fd.append("file", filetype);
$.ajax({
type: "POST",
url: base_url + "applicant_w/upload_docu_by_type",
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
}
})
controller
public function upload_docu_by_type() {
$this->load->helper(array('form', 'url'));
$F = array();
$prop_id = sanitize($this->input->post('prop_id'));
$file = sanitize($this->input->post('file'));
i want to get it in controller.
Use below code snipped, hope it work for you!
$("input[name='prop_id']").val();
I think this will work in JS:
document.getElementsByName("prop_id")[0].value;
prop_id = document.getElementsByName("prop_id")[0].value;
console.log(prop_id);
<input type="text" name="prop_id" value="test">

data in onchange to be moved/passed to onclick

I have an on event in input type file i do it like this
$("#image").on("change", function(e) {
var name = $("#filename").val();
var file = e.target.files[0];
var filename = name.length > 1 ? name : file.name;
var filetype = file.type;
var filesize = file.size;
var datafile = {
"filename":filename,
"filetype":filetype,
"filesize":filesize
};
console.log(datafile);
console.log(file);
});
also i have an onclick event where i have an ajax that send data to a php file where i save the information
i do it like this
$(document).on('click', '#add', function() {
var id= $('#id').val();
var name = $('#name').val();
var address= $('#address').val();
$.ajax({
type: 'POST',
url: '../include/save.php',
dataType: "json",
data: {
id: id,
name: name,
address: address
},
success: function(data) {
console.log(data);
}
},
error: function(data) {
alert('Error! ');
}
});});
i want to add the data in onchange in onclick so i can save the image or pdf file in database.How can i use the data on onchange event?I mean how can i be able to access the data in onchange event from onclick even? How is this possible any idea is appreciated
UPDATE
html
<input type="file" id="image" accepts=".pdf" />
<input type='text' id="filename" name='filename' maxlength="15" value="" class=' InputBoxF'/>
As suggested by Fuzzyma, one solution could be to make global variable. What i want to propose is, passing data using custom events. I have made a simple fiddle to explain the concept and used a dummy data to be passed. Take a look at below fiddle:
http://jsfiddle.net/da833p6j/1/
$("#image").on("change", function(e) {
//DummyData
var datafile = {
"filename":'xyz',
"filetype":'txt',
"filesize": '2KB'
};
var e = $.Event("passData");
//Trigger the custom event along with the dummyData
$(this).trigger(e,[datafile] );
});
$(document).on('passData', function(e, param){
//Attaching passed data to DOM Element
$('#filename').data('someData', param);
});
$('#add').on("click", function(){
var fileData= $('#filename').data('someData');
$.ajax({
type: 'POST',
url: '../include/save.php',
dataType: "json",
data : fileData,
success: function(data) {
console.log(data);
},
error: function(data) {
alert('Error! ');
}
});
});
To know more about custom events in jquery, you can checkout this link CreateEvent
You have to declare your variables in the outer scope from both functions to make them defined in the functions.
(function(){
var file, filename, filtype, filesize, datafile;
$("#image").on("change", function(e) {
var name = $("#filename").val();
file = e.target.files[0];
filename = name.length > 1 ? name : file.name;
filetype = file.type;
filesize = file.size;
datafile = {
"filename":filename,
"filetype":filetype,
"filesize":filesize
};
console.log(datafile);
console.log(file);
});
$(document).on('click', '#add', function() {
// Here you can access the variables now
var id= $('#id').val();
var name = $('#name').val();
var address= $('#address').val();
$.ajax({
type: 'POST',
url: '../include/save.php',
dataType: "json",
data: {
id: id,
name: name,
address: address
},
success: function(data) {
console.log(data);
},
error: function(data) {
alert('Error! ');
}
});
});
})();
However you may have to check in the click-handler if the variable has a correct value
EDIT:
Fixed your ajax-code
Added self-invoking function

Make Ajax Post when val on input changes and checkbox is checked

I have 3 input fields:
Title: <input type="text" value="Testa Ieraksts" id="blog_title"><br>
Check: <input type="checkbox" value="" id="blog_url_change"><br>
URL: <input type="text" value="" id="blog_slug" disabled="disabled"><br>
GOAL: When Checkbox is checked input#blog_slug is set to non-disabled, and then i want on input#blog_title changes send ajax post with var DATA.
jQuery(document).ready(function($){
$('input#blog_url_change').click(function(){
$('input#blog_slug').attr('disabled', !$(this).attr('checked'));
var STATUS = $('input#blog_url_change').prop('checked');
if (STATUS === true) {
$('input#blog_title').on('change', function() {
var DOMAIN = window.location.hostname;
var DATA = this.value;
$.ajax({
type: 'POST',
url: "http://" + DOMAIN + "/blog/helper/geturl",
data: 'data=' + DATA,
dataType: 'json',
success: function (response) {
console.log(response.url);
$('input#blog_slug').val(response.url);
},
}); // End Ajax
});
}
});
});
Problem: I need post only when checkbox is checked and title input val changes.
How to link these mothods together?
Thanks For #iCore ;)
$('input#blog_title').on('change', function() {
$('input#blog_url_change').click(function(){
$('input#blog_slug').attr('disabled', !$(this).attr('checked'));
var STATUS = $('input#blog_url_change').prop('checked');
console.log(STATUS);
if (STATUS === true) {
var DOMAIN = window.location.hostname;
var DATA = $('input#blog_title').val();
$.ajax({
type: 'POST',
url: "http://" + DOMAIN + "/blog/helper/geturl",
data: 'data=' + DATA,
dataType: 'json',
success: function (response) {
console.log(response.url);
$('input#blog_slug').val(response.url);
},
}); // End Ajax
}// End If
});
});

Ajax post multiple variables via loop?

I am trying to post multiple variables from the already dynamically create-able "username" id's such as "username1", "username2", etc. I'm looking for a way to dynamically send these into ONE ajax post request. My problem is mainly with the data parameter.
var numOfInputs = $('input').length;
$.ajax({
type: "POST",
url: "ajax.php",
// need way to dynamically pass more of these via numOfInputs.
data: ({username1 : $('#username1').val()}),
success: function(msg){
$('#statuses').html(msg);
}
});
requested html:
<input type="text" id="username1"></input><button id="add">+</button><button id="check">Check</button>
<div id="added-fields">
</div>
<div id="statuses">
</div>
var data = {};
for (var i = 1; i <= numOfInputs; i++) {
data["username" + i] = $("#username" + i).val();
}
$.ajax(
...
data: data,
....
)
Well you can say:
$.ajax({
type: "POST",
url: "ajax.php",
data: $('input').map(function() {
var o = {};
o[this.id] = this.value;
return o;
});
...

Categories

Resources