2 Dropzone on the same page - javascript

Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
script
<code>
var Onyx = {
defaults: {
debug: true
},
/**
* Function to print results in the console if the above debug is true
**/
log: function() {
if (Onyx.defaults.debug === true) {
var argsArray = [],
printOut = "console.log(args)";
for ( var i = 0; i < arguments.length; i++ ) {
argsArray.push("args[" + i + "]");
}
printOut = new Function( "args", printOut.replace( /args/, argsArray.join(",") ) );
printOut(arguments);
}
},
/**
* Firing functions and bindings and other important stuff
**/
init: function(e) {
if ( $("#the-planner-form").length ) {
Onyx.projectPlanner();
if ( $("body").data("form-completed") == "yes" ) {
setTimeout(function() {
Onyx.plannerShowSuccess(true)
}, 800)
}
}
},
/**
* Project planner
**/
projectPlanner: function() {
Onyx.initDropzone();
var checkedValues = [];
// Add default checked service
$('input[name="planner_project_type_checkbox"]:checked').each(function() {
$(this).val();
checkedValues.push($(this).val())
});
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
$('div.type-selection').each(function() {
$(this).on("click", function(e) {
e.preventDefault();
if ( $(this).find('input[checked]').length ) {
checkedValues.splice( $.inArray($(this).find('input[checked]').val(), checkedValues), 1 );
$(this).find('input[checked]').removeAttr('checked');
$('input[name="planner_project_type"]').val(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
Onyx.log(checkedValues);
} else {
$(this).find('input[name="planner_project_type_checkbox"]').attr('checked', true);
checkedValues.push($(this).find('input[name="planner_project_type_checkbox"]').val());
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
Onyx.log(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
}
});
});
var sendingForm = false;
$("form#the-planner-form").bind("submit", function(e) {
e.preventDefault();
// Check every thing is valid
$('form#the-planner-form').find(".validate").each(function() {
sendingForm = 0 != Onyx.plannerValidate($(this));
});
if (sendingForm) {
$(".error-msg").stop().animate({
opacity: 0
}, 300, function () { $(this).hide() });
if ( matchMedia("only screen and (max-height: 1023px)").matches || matchMedia("only screen and (max-width: 600px)").matches ) {
$("html,body").stop().animate({
scrollTop: 0
}, 500);
}
Onyx.plannerShowSpinner();
$.ajax({
type: "POST",
url: window.location + "/send_form.php",
data: $("#the-planner-form").serialize()
}).done(function (status, textStatus, jqXHR) {
Onyx.log("Planner form status: " + status);
Onyx.log("Planner form textStatus: " + textStatus);
Onyx.log(jqXHR);
if ( jqXHR.status == 200 && textStatus == 'success' ) {
Onyx.plannerShowSuccess();
} else {
Onyx.plannerShowSpinner(false);
alert("Something went wrong");
}
});
} else {
$(".error-msg").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300), false
}
});
},
plannerShowSpinner: function(showSpinner) {
if ("undefined" == typeof showSpinner) var showSpinner = true;
if ( showSpinner ) {
$(".form-controls, .fields-group").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide();
$(".form-spinner").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
});
} else {
$(".form-spinner").stop().animate({
opacity: 1
}, 300, function() {
$(this).hide();
$(".form-controls, .fields-group").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 400)
});
}
},
plannerShowSuccess: function(showSuccess) {
if ("undefined" == typeof showSuccess) var showSuccess = false;
var showThankyou = function() {
$(".form-spinner").stop().animate({
opacity: 0
}, 150, function() {
$(this).hide();
$(".form-thankyou-wrap").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
})
};
showSuccess ? $(".form-controls").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide(), showThankyou()
}) : showThankyou()
},
/**
* Upload button
**/
dropzone_active: false,
updateDropzoneCount: function() {
var uploadedCount = $(".dz-preview.dz-success").length,
finalText = "";
if ( uploadedCount == 1 ) {
finalText = uploadedCount + " Archivo Subido.";
} else if ( uploadedCount == 0 ) {
finalText = "No subiste ningún archivo.";
} else {
finalText = uploadedCount + " Archivos Subidos.";
}
$(".total-uploaded").text(finalText)
},
initDropzone: function(e) {
Dropzone.autoDiscover = false;
Dropzone.options.plannerFilesDropzone = {
paramName: "form_file",
maxFilesize: 10,
maxFiles: 5,
acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf",
url: window.location + "/file-upload.php",
addRemoveLinks: true,
forceFallback: false,
clickable: true,
/**
* The text used before any files are dropped.
*/
dictDefaultMessage: "Drop files here to upload.", // Default: Drop files here to upload
/**
* The text that replaces the default message text it the browser is not supported.
*/
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", // Default: Your browser does not support drag'n'drop file uploads.
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/
dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", // Default: File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.
/**
* If the file doesn't match the file type.
*/
dictInvalidFileType: "You can't upload files of this type.", // Default: You can't upload files of this type.
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/
dictResponseError: "Server responded with {{statusCode}} code.", // Default: Server responded with {{statusCode}} code.
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/
dictCancelUpload: "Cancel upload.", // Default: Cancel upload
/**
* The text that is displayed if an upload was manually canceled
*/
dictUploadCanceled: "Upload canceled.", // Default: Upload canceled.
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", // Default: Are you sure you want to cancel this upload?
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/
dictRemoveFile: "Remove file", // Default: Remove file
/**
* If this is not null, then the user will be prompted before removing a file.
*/
dictRemoveFileConfirmation: null, // Default: null
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/
dictMaxFilesExceeded: "You can not upload any more files.", // Default: You can not upload any more files.
/**
* Allows you to translate the different units. Starting with `tb` for terabytes and going down to
* `b` for bytes.
*/
dictFileSizeUnits: {tb: "TB", gb: "GB", mb: "MB", kb: "KB", b: "b"},
init: function() {
Onyx.dropzone_active = true;
$("input[name=form_file]").remove();
this.on("addedfile", function(file) {
$('button[type="submit"]').attr("disabled", "disabled");
Onyx.updateDropzoneCount();
});
this.on("removedfile", function(file) {
Onyx.log('Start removing file!');
$.ajax({
type: "POST",
url: window.location + "/file-upload.php",
data: {
target_file: file.upload_ticket,
delete_file: 1
},
sucess: function(jqXHR, textStatus){},
complete: function(jqXHR, textStatus){
var response = JSON.parse(jqXHR.responseText);
// Handle success
if (response.status === 'success') {
Onyx.log('Success: ' + response.info);
}
// Handle error
else {
Onyx.log('Error: ' + response.info);
}
}
});
var inputField = $("input[name=form_files_list]"),
filesArray = inputField.val().split(","),
fileIndex = $.inArray(file.upload_ticket, filesArray);
fileIndex !== -1 && filesArray.splice(fileIndex, 1);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
Onyx.updateDropzoneCount();
});
this.on("success", function(file, response) {
let parsedResponse = JSON.parse(response);
file.upload_ticket = parsedResponse.file_link;
var inputField = $("input[name=form_files_list]"),
filesArray = [];
Onyx.log(file.upload_ticket);
if ( "" != inputField.val() ) {
filesArray = inputField.val().split(",");
}
filesArray.push(file.upload_ticket);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
// Something to happen when file is uploaded
});
this.on("complete", function(file) {
if ( 0 === this.getUploadingFiles().length && 0 === this.getQueuedFiles().length ) {
$('button[type="submit"]').removeAttr("disabled");
}
Onyx.updateDropzoneCount()
});
this.on("error", function(file, t, a) {
this.removeFile(file);
});
}
};
$("#planner-files-dropzone").dropzone();
$("#planner-files-dropzone .instructions").click(function(e) {
var t = Dropzone.forElement("#planner-files-dropzone");
t.hiddenFileInput.click();
e.preventDefault()
})
},
plannerValidate: function(e) {
if ("" == e.val()) return e.addClass("error"), false;
if (!e.is('[type="email"]')) return e.removeClass("error"), true;
var t = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e.val());
return t ? void 0 : (e.addClass("error"), false)
}
};
$(function() {
Onyx.init();
});
<?php
$delete_file = 0;
if(isset($_POST['delete_file'])){
$delete_file = $_POST['delete_file'];
}
$targetPath = dirname( __FILE__ ) . '/uploads/';
// Check if it's an upload or delete and if there is a file in the form
if ( !empty($_FILES) && $delete_file == 0 ) {
// Check if the upload folder is exists
if ( file_exists($targetPath) && is_dir($targetPath) ) {
// Check if we can write in the target directory
if ( is_writable($targetPath) ) {
/**
* Start dancing
*/
$tempFile = $_FILES['form_file']['tmp_name'];
$targetFile = $targetPath . $_FILES['form_file']['name'];
// Check if there is any file with the same name
if ( !file_exists($targetFile) ) {
// Upload the file
move_uploaded_file($tempFile, $targetFile);
// Be sure that the file has been uploaded
if ( file_exists($targetFile) ) {
$response = array (
'status' => 'success',
'file_link' => $targetFile
);
} else {
$response = array (
'status' => 'error',
'info' => 'Couldn\'t upload the requested file :(, a mysterious error happend.'
);
}
/*$response = array (
'status' => 'success',
'file_link' => 'Just a test, don\'t take it seriously.'
);*/
} else {
// A file with the same name is already here
$response = array (
'status' => 'error',
'info' => 'A file with the same name is exists.',
'file_link' => $targetFile
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'The specified folder for upload isn\'t writeable.'
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'No folder to upload to :(, Please create one.'
);
}
// Return the response
echo json_encode($response);
exit;
}
// Remove file
if( $delete_file == 1 ){
$file_path = $_POST['target_file'];
// Check if file is exists
if ( file_exists($file_path) ) {
// Delete the file
unlink($file_path);
// Be sure we deleted the file
if ( !file_exists($file_path) ) {
$response = array (
'status' => 'success',
'info' => 'Successfully Deleted.'
);
} else {
// Check the directory's permissions
$response = array (
'status' => 'error',
'info' => 'We screwed up, the file can\'t be deleted.'
);
}
} else {
// Something weird happend and we lost the file
$response = array (
'status' => 'error',
'info' => 'Couldn\'t find the requested file :('
);
}
// Return the response
echo json_encode($response);
exit;
}
?>
<form action="#" method="post" id="the-planner-form" enctype="multipart/form-data">
<div class="text-cotizador">
<h1>COTIZADOR ONLINE</h1>
</div>
<div class="img-cotizador">
<img src="images/barrita-dorada.png" alt="ubicacion" width="35" height="5">
</div>
<div class="text-cotizador">
<p>Envíenos la foto de la joya a cotizar, y un tasador especializado<br>
la analizará y le brindará <b>el mejor precio del mercado.</b>
</p>
</div>
<div class="fields-group clearfix">
<div class="fields-group-controls1">
<div class="form-field half first">
<input type="text" name="planner_name" id="name" class="validate" placeholder="Nombre">
</div>
</div>
<div class="fields-group-controls2">
<div class="form-field half first">
<input type="email" name="planner_email" id="email" class="validate" placeholder="E-mail">
</div>
<div class="form-field half last">
<input type="tel" name="planner_phone" id="phone" class="validate" placeholder="Telefono">
</div>
</div>
<div class="fields-group-controls">
<div class="form-field">
<textarea name="planner_project_description" id="description" class="validate" placeholder="Comentarios"></textarea>
</div>
<div class="form-field">
<div id="files-wrap">
<div id="planner-files-dropzone">
<div class="dropzone-foo">
<div class="instructions is-desktop">ARRASTRA Y SUELTA AQUÍ LOS ARCHIVOS</br>o</div>
<div class="instructions is-touch">Subi los archivos</div>
</div>
<div class="total-uploaded">No se ha seleccionado ningún archivo</div>
</div>
<input type="hidden" value="" name="form_files_list" />
<input type="file" name="form_file" id="pp-file" />
</div>
<div class="text-formatos">
<p>Puede seleccionar hasta 5 imágenes | Tamaño máximo por imagen: 100 MB<br>Formatos admitidos: gif, png, jpg, jpeg
</p>
</div>
</div>
</div>
</div>
<div class="form-spinner-container">
<div class="form-spinner"></div>
</div>
<div class="form-thankyou-wrap">
<div class="form-thankyou-wrap-inner">
<div class="form-thankyou-content">
<h2><em>Gracias!</em> su mensaje ha sido enviado correctamente.</h2>
<p>Te contactaremos en poco tiempo..</p>
Go back to home page
</div>
</div>
</div><!-- .form-thankyou-wrap -->
<div class="form-controls">
<button aria-label="Send" type="submit">Enviar</button>
<div class="error-msg">Debe diligenciar toda la información. ↑</div>
</div>
</form>

Related

How to upload in a particular folder of google drive?

I am having html form and gs.code as shown below. Its working perfect but files are uploaded in root folder of google drive. I want my files to upload in particular folder. Please help me.
Even i want to know how to use uploadView.setIncludeFolders(true) to show particular folder and subfolder for selection and upload.
var config = {
DEVELOPER_KEY: 'xxxx',
UPLOAD_FOLDER_ID: 'xxx',
ACCEPTED_FOLDER_ID: 'xxx',
TIME_ZONE: "GMT",
DATE_FORMAT: "MM/dd/yyyy HH:mm:ss",
ALLOWED_FILES: [
// MimeType.BMP,
// MimeType.GIF,
MimeType.pdf
// MimeType.PNG,
// MimeType.SVG,
// MimeType.PDF,
// MimeType.CSS,
// MimeType.CSV,
// MimeType.HTML,
// MimeType.JAVASCRIPT,
// MimeType.PLAIN_TEXT,
// MimeType.RTF,
// MimeType.OPENDOCUMENT_GRAPHICS,
// MimeType.OPENDOCUMENT_PRESENTATION,
// MimeType.OPENDOCUMENT_SPREADSHEET,
// MimeType.OPENDOCUMENT_TEXT,
// MimeType.MICROSOFT_EXCEL,
// MimeType.MICROSOFT_EXCEL_LEGACY,
// MimeType.MICROSOFT_POWERPOINT,
// MimeType.MICROSOFT_POWERPOINT_LEGACY,
// MimeType.MICROSOFT_WORD,
// MimeType.MICROSOFT_WORD_LEGACY,
// MimeType.ZIP
]
}
function doGet( e ){
return HtmlService.createHtmlOutputFromFile( "Form.html" ).setSandboxMode( HtmlService.SandboxMode.IFRAME )
}
function getConfig(){
DriveApp.getRootFolder();
return {
DEVELOPER_KEY: config.DEVELOPER_KEY,
TOKEN: ScriptApp.getOAuthToken(),
UPLOAD_FOLDER_ID: config.UPLOAD_FOLDER_ID
}
}
function verifyUpload( upload ){
var acceptedFolder = DriveApp.getFolderById( config.ACCEPTED_FOLDER_ID ),
uploadFolder = DriveApp.getFolderById( config.UPLOAD_FOLDER_ID ),
date = Utilities.formatDate( new Date(), config.TIME_ZONE, config.DATE_FORMAT ),
success = [],
fail = [],
doc,
file,
name
for( var i = 0; i < upload.docs.length; i++ ){
doc = upload.docs[ i ];
file = DriveApp.getFileById( doc.id );
name = file.getName();
if ( config.ALLOWED_FILES.indexOf( doc.mimeType ) >= 0 ){
success.push( name );
acceptedFolder.addFile( file );
uploadFolder.removeFile( file );
} else {
fail.push( name );
}
file.setName( upload.username + " - " + date + " - " + name);
}
return {
success: success,
fail: fail
}
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<style>
.app {
margin: 50px 0 0 30px;
}
.formholder {
background-color: #eee;
padding: 25px;
min-width: 400px;
max-width: 40%
}
input[type="text"] {
width: 300px;
}
</style>
</head>
<html>
<body>
<div class="app">
<div class="block formholder">
<div class="block form-group">
<label for="username">Name<span class="current">*</span>
</label>
<input type="text" id="username" class="width-100">
</div>
<div class="block">
<button class="blue" id="run-filepicker-interface">Choose File/s to Upload</button>
</div>
<div class="block">
</a>
</div>
</div>
<div class="block">
<div class="block" id="success-output"></div>
<div class="block error" id="error-output"></div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var fileUploadApp = {
config: {
DIALOG_DIMENSIONS: {
width: 600,
height: 425
}
},
init: function() {
google.script.run
.withSuccessHandler(fileUploadApp.setup)
.withFailureHandler(fileUploadApp.system.outputError)
.getConfig()
},
setup: function(config) {
$.extend(fileUploadApp.config, config)
gapi.load('picker', {
'callback': function() {
$('#run-filepicker-interface').click(fileUploadApp.runFilePickerInterface);
}
});
},
runFilePickerInterface: function(event) {
fileUploadApp.system.clearOutput()
var username = $("#username").val()
if (username) {
var config = fileUploadApp.config
$('#run-filepicker-interface').prop("disabled", false)
var uploadView = new google.picker.DocsUploadView()
uploadView.setIncludeFolders(false)
var picker = new google.picker.PickerBuilder()
.addView(uploadView)
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.hideTitleBar()
.setOAuthToken(config.TOKEN)
.setDeveloperKey(config.DEVELOPER_KEY)
.setCallback(fileUploadApp.pickerCallback)
.setSize(config.DIALOG_DIMENSIONS.width, config.DIALOG_DIMENSIONS.height)
.setOrigin(google.script.host.origin)
.setSelectableMimeTypes('application/vnd.google-apps.folder')
.build();
picker.setVisible(true);
} else {
fileUploadApp.system.outputError("Name is required.")
}
},
pickerCallback: function(data) {
switch (data.action) {
case google.picker.Action.PICKED:
var upload = {
username: $("#username").val(),
docs: []
}
$.each(data.docs, function(index, value) {
if (value.uploadState == "success")
upload.docs.push({
id: value.id,
mimeType: value.mimeType
})
})
google.script.run
.withSuccessHandler(fileUploadApp.verifyUploadSuccess)
.withFailureHandler(function(msg) {
$('#run-filepicker-interface').prop("disabled", false)
fileUploadApp.system.outputError(msg)
})
.verifyUpload(upload)
fileUploadApp.system.outputSuccess("Verifying uploaded files.")
break;
case google.picker.Action.CANCEL:
$('#run-filepicker-interface').prop("disabled", false)
break;
case google.picker.Action.LOADED:
// actions here
break;
}
},
verifyUploadSuccess: function(verifyResult) {
fileUploadApp.system.clearOutput()
if (verifyResult.success.length) {
fileUploadApp.system.outputSuccess(
"Fail:<br />" +
verifyResult.success.join("<br />")
)
}
if (verifyResult.fail.length) {
fileUploadApp.system.outputError(
"Success:<br />" +
verifyResult.fail.join("<br />")
)
}
$('#run-filepicker-interface').prop("disabled", false)
},
system: {
outputError: function(msg) {
$("#error-output").html(msg)
},
outputSuccess: function(msg) {
$("#success-output").html(msg)
},
clearOutput: function() {
$("#error-output, #success-output").html("")
}
}
}
function init() {
fileUploadApp.init()
}
</script>
<script src="https://apis.google.com/js/api.js?onload=init"></script>
</html>

Laravel 7 - Uncaught ReferenceError: Dropzone is not defined

I have a form that uses Dropzone for uploading images. The framework used is Laravel 7. The images are uploaded regularly to the store and inserted into the database, but in the console I get the following error:
Uncaught ReferenceError: Dropzone is not defined.
Also the page does not refresh or redirect.
View
<form data-single="true" data-file-types="image/jpeg|image/png|image/jpg" action="inserisci_avatar" class="dropzone " id="dropzone-avatar" method="POST" >
#csrf
<div class="fallback">
<input name="avatar" type="file" />
</div>
<div class="dz-message" data-dz-message>
<div class="text-lg font-medium">Trascina il tuo avatar qui.</div>
<div class="text-gray-600"> Oppure clicca e seleziona il file </div>
</div>
</form>
<script>
window.onload = function() {
//Dropzone.autoDiscover = false;
Dropzone.options.dropzoneAvatar = {
maxFilesize: 12,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 5000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
};
</script>
Controller:
public function ins_avatar(Request $request)
{
$azienda = Auth::user();
if ($request->hasFile('file')) {
$id = $azienda->azienda->id;
$ins_avatar = Azienda::find($id);
if ($ins_avatar->avatar != null) {
$cancella = $ins_avatar->avatar;
Storage::delete('public/' . $cancella);
}
$path = $request->file('file')->store('uploads/avatar', 'public');
$ins_avatar->avatar = $path;
$ins_avatar->save();
$ok = 'ok';
return response()->json(['success' => $ok]);
} else {
return back()->with('avatar modificato', 'Nessuna immagine è stata caricata');
}
}
Grazie

Problem in adding data through admin.firestore()

My current firestore rules in my project:
service cloud.firestore {
match /databases/{database}/documents {
match /auth_url/{auth_doc} {
allow read, write: if request.auth.uid != null;
}
match /nonauth_url/{nonauth_doc}{
allow read, write: if false ;
}
}
}
auth_url collection is for authorized users and running perfectly (addition, creation, deletion etc of documents) and nonauth_url collection is for non authenticated users, by jquery post request through client.js I'm adding data by using admin.firestore() in my server (index.js) but in my cloud firestore section there is no data present there. Are my firestore rules wrong somewhere ?
client.js
function renderList(user){
let db = firebase.firestore() ;
stopListner = db.collection('auth_url').doc(user.email).onSnapshot( (doc) => {
var objOfObj = doc.data() ;
let newarrOfObjects = [] ;
for( key in objOfObj){
newarrOfObjects.push(Object.assign(objOfObj[key], {name: key})) ;
}
$('.container.urlsList').html('') ;
newarrOfObjects.forEach( (obj, pos) => {
if( obj.code != ''){
$('.container.urlsList').append(`
<div id="accordion${pos+1}" class="myUrlSlot">
<div class="card">
<div class="card-header d-flex flex-row align-items-center p-2">
<button class="btn btn-outline-dark rounded-circle" data-toggle="collapse" data-target="#${pos+1}"><i class="fa fa-plus"></i></button>
<div class="w-100 code font-weight-bold">
${obj.code}
</div>
<button data-edit-id="${pos+1}"class="btn btn-outline-primary edit rounded-circle"><i class="fa fa-pencil"></i></button>
<button data-del-id="${pos+1}" class="btn btn-outline-danger del rounded-circle"><i class="fa fa-trash"></i></button>
</div>
<div id="${pos+1}" class="collapse info">
<dl class='m-3'>
<dt>Shortened URL</dt>
<dd>${window.location.origin+ '/' + obj.code}</dd>
<dt>Redirection URL</dt>
<dd class="redirectUrl">${obj.redirectUrl}</dd>
</dl>
</div>
</div>
</div>
`) ;
}
}) ;
if( $('div.urlsList').children().length == 0){
$('#emptyMsg').show() ;
}
else{
$('#emptyMsg').hide() ;
}
// changing plus to minus vice-versa
$('.collapse').on('show.bs.collapse', function(){
$(this).parent().find('.fa-plus').removeClass('fa-plus').addClass('fa-minus') ;
}).on('hidden.bs.collapse', function(){
$(this).parent().find('.fa-minus').removeClass('fa-minus').addClass('fa-plus') ;
}) ;
// edit icon
$('.edit').click(function(){
let target_id = $(this).data('edit-id') ;
bootbox.dialog({
title: 'Change Redirection URL',
centerVertical: true,
closeButton: false,
message: `
<form id="changeUrlForm">
<label for="inputUrl">Enter the New Url</label>
<input type="url" class="form-control text-center" id="inputUrl" name="iurl" placeholder="Enter URL Here">
</form>
`,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-danger'
},
ok: {
label: 'Ok',
className: 'btn-primary',
callback: function(){
$('#changeUrlForm').validate({
rules: {
iurl: {
required: true,
url: true
}
},
messages: {
iurl: {
url: 'Please enter a valid url with "http://" or "https://" first !!'
}
}
}) ;
if( $('#changeUrlForm').valid()){
let newurl = $('#inputUrl').val() ;
var objToBeUpdated = `url${target_id}` ;
var updateObj = {} ;
updateObj[`${objToBeUpdated}.redirectUrl`] = newurl ;
db.collection('auth_url').doc(user.email).update(updateObj).then( () => {
successAlert(`URL${target_id}'s redirection url updated successfully !!`) ;
}).catch( err => {
errorAlert(err.code, err.message) ;
}) ;
}
else{
$('label.error').addClass('text-danger');
return false ;
}
}
}
}
}) ;
}) ;
// del icon
$('.del').click(function(){
let target_id = $(this).data('del-id') ;
bootbox.confirm({
message: 'Are you sure you want to delete this saved URL ?',
centerVertical: true,
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function(result){
if(result){
var updateObj = {
[`url${target_id}`]: {
code: '',
redirectUrl: ''
}
} ;
db.collection('auth_url').doc(user.email).update(updateObj).then(() => {
successAlert(`URL${target_id} deleted successfully !!`) ;
}).catch( err => {
errorAlert(err.code, err.message) ;
});
}
}
}) ;
}) ;
}, (err) => {
errorAlert(err.code, err.message) ;
}) ;
}
$(function(){
// on authorization endering is working perfectly fine
firebase.auth().onAuthStateChanged( user => {
if( user ){
if( firebase.auth().currentUser.emailVerified == false ){
bootbox.dialog(verifyDialogSettings);
}
if( firebase.auth().currentUser.providerData[0].providerId === 'google.com'){
$('.changePass, .beforechangePass').hide() ;
}
refreshMainPage( user ) ;
// refreshUrls(user.email) ;
console.log('signed in state') ;
$('.login, #newurl, .mainTopic, .middle').hide() ;
$('.signOutButton, .settings, .welcomemsg, .image, .description, .urlsList').show() ;
// refresh the list
renderList(user) ;
}
else{
console.log('signed out state') ;
$('.signOutButton, .settings, .welcomemsg, .image, .description, .urlsList, #emptyMsg').hide() ;
$('.login, #newurl, .mainTopic, .middle').show() ;
}
});
$('.sendUrl').on('click', function(e){
e.preventDefault() ;
$('#nonauthForm').validate({
rules: {
url_nauth: {
required: true,
url: true
}
}
}) ;
if( $('#nonauthForm').valid()){
$.post('/nonauth_url',{
URL: $('#url').val()
},function(code, status){
if(status === 'success'){
$('#newurl').html(`
${window.location.origin+ '/'+ code}
`)
}
}) ;
}
else{
$('label.error').addClass('text-danger d-block mt-2');
}
}) ;
}) ;
index.js (server)
const functions = require('firebase-functions');
const admin = require('firebase-admin') ;
const express = require('express') ;
const urlId = require('shortid') ;
const sp = require('synchronized-promise') ;
const string = require('randomstring') ;
const serviceAccount = require('./url-shortner-xxxx.json') ;
const app = express() ;
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let db = admin.firestore() ;
let Data = db.collection('nonauth_url') ;
app.post('/nonauth_url', (req, res) => {
let codeGenerated = 'n' + urlId.generate() ; // n for non-authenticated users
let docname = 'doc-' + string.generate(4) ;
let schema = {
code: codeGenerated,
url: req.body.URL,
expiredAt: Date.now()+600000 // in milisceonds for 10min
}
let docRef = Data.doc(docname).set(schema) ;
res.send(schema.code) ;
}) ;
exports.routeFunc = functions.https.onRequest(app) ;
res.send(schema.code) is sending back the code but not creating any docs under nonauth_url collection
Sending an HTTP response indicates the end of execution for a running function. You need to wait for the set() to complete before responding:
let docRef = Data.doc(docname).set(schema).then(() => {
res.send(schema.code);
});

How add WP comments via AJAX

I what create custom wordpress reply comment form and send data via ajax js , but when i send data to back are comments not show in admin panel. But status sending data is "OK" ( i cheked chrome console -> network ), how i can connect correctly front whith backend ? Whehere my mistake in this code ?
html
<div class="reply_comments respoond" style="display: none;">
<a class="cancel-comment-reply-link" style="display:none;">Cancel</a>
<form class="comment-form fcommentform">
<div class="comment-form-field-plus">
<label>Name:</label>
<input type="text" class="author" name="name">
<label>Email:</label>
<input type="text" class="email" name="email">
<textarea name="comment" class="comment" rows="5" cols="5" required></textarea>
</div>
<div class="form-footer">
<input class="like-post-button submit-comment-button rsubmit" type="button" value="<?php echo __('POST MY REVIEW', 'slotstory.com'); ?>" />
</div>
</form>
</div>
js
$('.rsubmit').on('click', function() {
$(this).closest('.fcommentform').submit();
});
$('.fcommentform').on('submit', function(e){
var errors = {
'name' : true,
'email' : true,
'comment' : true
};
e.preventDefault();
$(this).find('[name]').each(function( index ) {
var name = $( this ).attr('name');
var functionName = false;
switch(name){
case 'name':
functionName = _validateField;
break;
case 'email':
functionName = _validateEmail;
break;
case 'comment':
functionName = _validateComment;
break;
}
if (functionName) {
functionName.call(this);
$( this ).on('input', functionName.bind(this));
}
});
function _validateEmail(){
if(this != document) {
$element = $( this );
var reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!reg.test($element.val())) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateField(){
if(this != document) {
$element = $( this );
if ($element.val() == '') {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateComment(){
if(this != document) {
$element = $( this );
if ($element.val().length <= 10) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
if (Object.keys(errors).length == 0) {
console.log('success');
}
$.ajax({
type : 'POST',
url: ajaxactionurl,
data: $(this).serialize() + '&action=ajaxcomments',
error: function (request, status, error) {
if( status == 500 ){
alert( 'Error while adding comment' );
} else if( status == 'timeout' ){
alert('Error: Server doesn\'t respond.');
} else {
var wpErrorHtml = request.responseText.split("<p>"),
wpErrorStr = wpErrorHtml[1].split("</p>");
alert( wpErrorStr[0] );
}
},
});
return false;
});
php
add_action( 'wp_ajax_ajaxcomments', 'custom_submit_ajax_comment' );
add_action( 'wp_ajax_nopriv_ajaxcomments', 'custom_submit_ajax_comment' );
function custom_submit_ajax_comment() {
global $wpdb;
$comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
if ( is_wp_error( $comment ) ) {
$error_data = intval( $comment->get_error_data() );
if ( ! empty( $error_data ) ) {
wp_die( '<p>' . $comment->get_error_message() . '</p>', __( 'Comment Submission Failure' ), array( 'response' => $error_data, 'back_link' => true ) );
} else {
wp_die( 'Unknown error' );
}
}
$comment_data = array(
'comment_post_ID' => $comment_post_ID,
'comment_content' => $comment,
'comment_parent' => $comment_parent,
'comment_date' => $time,
'comment_approved' => 0,
'user_id' => $current_user->ID,
);
exit();
}
The status is 200 ok because you don't send anything in the php.
I suggest checking the body of the response, not just the status code.
Start debugging there. Good luck.

jQuery-File-Upload - Output

I use the jQuery-File-Upload. The form data is written to the database as I want to.
But when I upload an image I receive the following message:
{"files":[{"name":"1430606695-9544","size":0,"type":"","error":"No file was uploaded"}]}
Why does it say "No file was uploaded" etc.?
index.php:
<?php
/*
* jQuery File Upload Plugin PHP Example 5.14
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
$options = array(
'delete_type' => 'POST',
'db_host' => 'localhost',
'db_user' => 'helloworld',
'db_pass' => 'helloworld',
'db_name' => 'helloworld',
'db_table' => 'files'
);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function initialize() {
$this->db = new mysqli(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name']
);
parent::initialize();
$this->db->close();
}
protected function handle_form_data($file, $index) {
$file->title = #$_REQUEST['title'][$index];
$file->description = #$_REQUEST['description'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `title`, `description`)'
.' VALUES (?, ?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sisss',
$file->name,
$file->size,
$file->type,
$file->title,
$file->description
);
$query->execute();
$file->id = $this->db->insert_id;
}
return $file;
}
protected function set_additional_file_properties($file) {
parent::set_additional_file_properties($file);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = 'SELECT `id`, `type`, `title`, `description` FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $file->name);
$query->execute();
$query->bind_result(
$id,
$type,
$title,
$description
);
while ($query->fetch()) {
$file->id = $id;
$file->type = $type;
$file->title = $title;
$file->description = $description;
}
}
}
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $name);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
}
$upload_handler = new CustomUploadHandler($options);
basic-plus.html
<form id="fileupload" action="server/php/" method="POST" enctype="multipart/form-data">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
<label class="title">
<span>Title:</span><br>
<input name="title[]" class="form-control" value="testtitel">
</label>
<label class="description">
<span>Description:</span><br>
<input name="description[]" class="form-control" value="testdescription">
</label>
</form>
<script>
/*jslint unparam: true, regexp: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
main.js
/*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
url: 'server/php/'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
});
}
});
what does your network stack say?
ie: go to the "developer" view in chrome, (view->Developer->Developer Tools),
and open up the "network" tab, and try to do an upload, and look at the request, response, etc.
that may shed a lot of light.
I have used this plugin with javascript and java, but not with php.
also: find a really simple example that uploads a file (with php, if you need to use that), and start building out from there.

Categories

Resources