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
Related
I'm having a problem when using the jQuery .each() and .ajax() functions together when i want to upload all input file to SharePoint document library .
function checkAttachments(NewlyCreatedItemId)
{
$("[type='file']").each(function(){
var FileUploaderID=$(this).attr("id");
var attachfor=$(this).attr("alt");
var file = document.getElementById(FileUploaderID.toString()).files[0];
if (file != undefined) {
uploadDocument(FileUploaderID,attachfor,NewlyCreatedItemId);
}
else {
alert('Please, upload attachments for ');
}
});
}
function uploadDocument(uploader,attachfor,createdID) {
var files = $("#"+uploader+"")[0].files;
if (files.length > 0) {
var fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "ClaimAttachments";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
var DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
FileLeafRef: DocFileName , //FileLeafRef --> Internal Name for Name Column
AttachFor : attachfor ,
RequestGUID : createdID
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!");
}
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
it uploads the file of the first file uploader only because when it reach to the ajax call in function (uploadFileToFolder) go to the next iteration, how to can solve it .
I am trying to fetch the records from the database using blur function. There are two input fields where this function triggers. I have used different names, variables, javascript, controller using laravel to fetch the records. I am able to fetch the records through ajax and successfully opens the modal. When the modal pop ups when the blur function triggers, it also triggers the function for the second field.
I just want to trigger the modal according to the field, where the blur triggers and not to trigger twice.
//input field: originS
<script type="text/javascript">
$(document).ready(function(){
var origin = "";
var _token = "";
var ovalue = "";
$('#originS').blur(function(){
ovalue = "";
origin = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchOrigin') }}',
data:{origin:origin, _token:_token},
success: function(response){
if(response){
$("#originSelect").modal('show');
console.log(response);
$(".result").html(response);
$(document).on('change', '#selectSuburb', function () {
ovalue = $(this).val();
if ($(this).is(':checked')) {
$('#originS').val(ovalue);
$("#originSelect").modal('hide');
$this.die('blur');
}
});
$('#originSelect').on('hidden.bs.modal', function (e) {
if (ovalue == "") {
$("#originS").val('');
$(".result").html(response);
}
});
}
},
});
});
});
</script>
//input field: destS
</script>
<script type="text/javascript">
$(document).ready(function(){
var dest = "";
var _token = "";
var dvalue = "";
$('#destS').blur(function(){
dvalue = "";
dest = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchdest') }}',
data:{dest:dest, _token:_token},
success: function(response){
if(response){
$("#destSelect").modal('show');
console.log(response);
$(".dresult").html(response);
$(document).on('change', '#selectSuburbdest', function () {
dvalue = $(this).val();
if ($(this).is(':checked')) {
$('#destS').val(dvalue);
$("#destSelect").modal('hide');
$this.die('blur');
}
});
$('#destSelect').on('hidden.bs.modal', function (e) {
if (dvalue == "") {
$("#destS").val('');
$(".dresult").html(response);
}
});
}
},
});
});
});
</script>
I am trying to save image file through signature pad. I want the name of the file to be an element from my div. Which changes accordingly. Here is my code. It is saving the image but the filename is blank(.png).
Javascript:
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
var p = document.getElementById('my_class').innerHtml;
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php:
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['p'];
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
Replace with your assignment with var p = document.getElementById('my_class').value;
Due to onrendered function is a callback, it may not get the document.getElementById('my_class').innerHtml properly. Please get echo out the $_POST['p'] to make sure proper filename is sent to PHP side.
get document.getElementById('my_class').innerHtml before call html2canvas function.
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:document.getElementById('my_class').innerText}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
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.