Add dynamic input field in ajax - javascript

Is there a way to put a dynamic input inside ajax? I am using hayageek jquery file upload. I wanted to add an input as hidden inside the form upload for replacing a file. Any help would be much appreciated.
The div that handles upload:
<div id="replacefile">Upload</div>
I wanted to put: <input type="text" name="replace">
$("#replacefile").uploadFile({
url : newurl,
fileName : "myfile",
returnType : "json",
dragDrop : true,
showFileCounter: false, // show numbered list of file
allowDuplicates: false,
multiple : true, //allow multiple file upload
showFileSize : false, // show file size
acceptFiles : "doc,pdf",
onSuccess : function(files,data,xhr,pd) {
// success
},
onError : function() {
// error
}
});

$("#replacefile").uploadFile({
url : newurl,
fileName : "myfile",
returnType : "json",
dragDrop : true,
showFileCounter: false, // show numbered list of file
allowDuplicates: false,
multiple : true, //allow multiple file upload
showFileSize : false, // show file size
acceptFiles : "doc,pdf",
onSuccess : function(files,data,xhr,pd) {
// success
var input=$('<input type="text" name="replace">');
$('#replacefile').find('form').append(input);
},
onError : function() {
// error
}
});

Related

Issue in grapesJS - Asset manager handling

I'm now working on grapesJS implementation in our application. I have gone through documents provided & some of the issues reported regarding the asset manager in Github, etc.. I was not able to show the list of uploaded images in the Asset manager after a hard refresh list disappears.
I have tried to upload files to AmazonS3, upload was ok & I get its response, also it is showing in the list. In this case, I was not able to edit images due to the CORS issue.
Later, I tried with the base64 encoded image. With this method, I was able to edit uploaded images. Also got it in the image listing. As I said earlier, the image list only available until a hard refresh. I think it is from the cache.
I have doubts in a few codes, can you help me out of it.
Here is the assetManager section code:
assetManager: {
storageType : '',
storeOnChange : true,
storeAfterUpload : true,
embedAsBase64 : true, // Make this false to upload image to AmazonS3
upload : siteURL+'assets/CONTENT/img', // For temporary storage, Upload endpoint, set `false` to disable upload
assets : [],
// headers: {}, // Custom headers to pass with the upload request
// params: {}, // Custom parameters to pass with the upload request, eg. csrf token
credentials: 'include', // The credentials setting for the upload request, eg. 'include', 'omit'
autoAdd : 1, // If true, tries to add automatically uploaded assets.
dropzone : 0, // Enable an upload dropzone on the entire editor (not document) when dragging files over it
openAssetsOnDrop : 1, // Open the asset manager once files are been dropped via the dropzone
multiUpload : true, // Allow uploading multiple files per request. If disabled filename will not have '[]' appended
showUrlInput: true, // Toggles visiblity of assets url input
uploadFile: function(e) {
// Ref: https://blog.webnersolutions.com/adding-image-upload-feature-in-grapesjs-editor/
var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
var formData = new FormData();
for(var i in files){
formData.append('file-'+i, files[i]); // Containing all the selected images from local
}
$.ajax({
url: siteURL + 'uploadImage_base64', // Save image as base64 encoded - Its a function
// url: siteURL + 'uploadImage', // Upload image to AmazonS3 - Its a function
type: 'POST',
data: formData,
contentType: false,
crossDomain: true,
dataType: 'json',
mimeType: "multipart/form-data",
processData: false,
success: function(result) {
var myJSON = [];
if ((typeof(result['data']) != 'undefined') && (result != 'null')) {
$.each(result['data'], function(key, value) {
myJSON[key] = value;
});
console.log(myJSON);
// while using base64 encode => 0: {name: "ipsumImage.png", type: "image", src: "data:image/png;base64,iVBORw0KGgAAVwA…AAAAAAAAAAAAAAAD4Pv4B6rBPej6tvioAAAAASUVORK5CYII=", height: 145, width: 348}
// while using AmazonS3 => 0: {name: "logo_sigclub.png", type: "image", src: "https://amazonaws.com/assets/CONTENT/img/logo_sigclub.png", status: true, message: "Uploaded successfully", …}
editor.AssetManager.add(myJSON); //adding images to asset manager of GrapesJS
}
}
});
}
}
I have doubt in:
upload : siteURL+'assets/CONTENT/img', is this image upload path or a function which uploads image?
If I'm using AmazonS3, can I able to get the editing option with the CORS issue?
How can I show the uploaded images in Asset Manager without disappearing later?

How to solve error parsing in dataTables?

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

Preprocess before kendo ui upload

I want to pass some data(a guid) to the upload method of the kendoUpload so that the particular MVC Controller action method will receive that data. Each time the upload happens, I need to pass this data (guid).
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
The field is fileId. I can call the above code block in a click event of the upload button and it works but the Kendo UI styles are not applied to the upload button at the initialization.
$("#propertyAttachmentUpload").click(
function() {
var fileId = guid();
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
});
How can I initialize the fileId without loosing the Kendo UI styles.
Note: I cannot call guid() inside upload method since the upload method calls for each uploading chunk. For all the chunks the fileId should be same for a particular file.
I've resolved this problem using a global variable and setting that variable in the click event of the upload button,
var fileGuid = '';
$(document).on('click', '#propertyAttachmentUpload', function() {
fileGuid = "";
fileGuid = guid();
})
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileGuid };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});

I am making an ajax call to load the contents into modal dialog; which seems to be working on all other browser than IE

I am making an ajax call to load the contents into modal dialog; which seems to be working on all other browser than Internet Explorer. In Internet Explorer it is freezing and I cannot do any thing I have to use Task Manager to end task. Can anyone tell me what can i do to resolve the freezing issue? The content that I am loading from the URL are dynamic HTML contents, which has scripts, etc.
try{
var LOCALE ='en_us';
var custNUm= 'Y0392287497';
var dURL = 'https://www.over.com?cstNum='+custNUm+'&loc='+LOCALE;
var mModal = $("<div class=\"mdialog\" role=\"dialog\"></div>").html('Loading Please Wait....').dialog({
position : [ 'center', 20 ],
modal : true,
//autoOpen : false,
bgiframe : true,
resizable: false,
closeOnEscape : false,
title : "CUSTOMER MODAL",
close : function(event, ui) {
$(this).remove();
}
});
$.ajax({
url : dURL,
type : 'POST',
dataType : 'text',
timeout : 5000,
beforeSend: function()
{
$('html,body').css('overflow', 'hidden');
},
error : function(xhr, status, error) {
alert(error);
},
success : function(textResponse) {
mcdpModal.html(textResponse);
}
});
}catch(e){
alert(e);
}
Want to the following: 1.Is ur Modal Window getting opened ?
2.Is your data response comming from ur server
3.Is this url u access resides in different domain ? (for 3 rd point:IE does not support Cross Domain AJAX Calls.You need to have both ur execution domain and the server domain to be same.)

Variable in Javascript for uploadify form data is undefined

Hi I need to save a variable in Javascript and give it to uploadify.
This is my code:
var mediaID;
$(".edit_photo_media").live("click", function() {
mediaID = $(this).data("media-id");
$.ajax({
url: 'edit.php?action=media_select',
type: 'GET',
dataType: 'html',
success: function (select) {
if (select == '3') {
document.location = "login.php";
} else {
$("#dialog_upload_media").dialog("open");
}
}
});
return false;
});
$('#file_upload').uploadify({
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.jpg;',
'fileSizeLimit' : '4096KB',
'debug' : true,
'method' : 'post',
'formData' : {'id' : '' + mediaID},
'swf' : 'include/swf/uploadify.swf',
'uploader' : 'include/scripts/upload_mult.php'
});
So everytime before the uploader is opened .edit_photo_media is clicked.
<img src="images/photo.png" />
This is where the var mediaID is getting its content. Inside .edit_photo_media mediaID is defined correct.
But if I click the upload button mediaID is undefined. Why is the variable loosing its value?
Edit: Ok this seems to be related to a uploadify bug? If I check mediaID on any other function it is working fine... rlly strange
Ok problem solved. Just added 'onUploadStart' and saved the id in there
$('#file_upload').uploadify({
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.jpg;',
'fileSizeLimit' : '4096KB',
'buttonText' : 'Bilder auswählen',
'debug' : true,
'method' : 'post',
'formData' : {'id' : 0},
'swf' : 'include/swf/uploadify.swf',
'uploader' : 'include/scripts/upload_mult.php',
'onUploadStart' : function(file) {
$('#file_upload').uploadify("settings", "formData", {"id": mediaID});
}
});
jQuery only started subsuming HTML5 data properties set in the source code from version 1.6 onwards. If you're using < 1.6, this won't happen, in which case upgrade jQ.

Categories

Resources