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.
Related
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>
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
Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>
views.php
<div class="input-group">
<input class="form-control" id="nomor_cari" maxlength="16" placeholder="No. CM / No. KTP">
script autocomplete
$('#nomor_cari').autocomplete({
source: get_no,
dataType: 'JSON'
});
function get_no
<?php
function get_no($q)
{
$this->db->select('NO_MEDREC');
$this->db->like('NO_MEDREC', $q);
$query = $this->db->get('PASIEN_IRJ');
if($query->num_rows > 0)
{
foreach ($query->result_array() as $row)
{
$row_set[] = htmlentities(ucfirst($row['NO_MEDREC']));
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($row_set));
}
echo $query->row();
}?>
but autocomplete didn't show anything.
if i use local variable , autocomplete works like it should be.
<script> var availableNumber = [
"0000000002",
"0000000020",
"0000000200",
"0000002000"
];
/<script>
and changes autocomplete to
$('#nomor_cari').autocomplete({
source: availableNumber,
dataType: 'JSON'
});
what did i missed? (im sure .js are loaded because when using local var , it works like charm)
just in case needed , here's my autoload
$autoload['libraries'] = array('database', 'email', 'session');
$autoload['helper'] = array('url', 'template', 'message', 'misc');
I think issue is in "source". Please try to use json like this
$('#nomor_cari').autocomplete({
source: function (request, response) {
$.getJSON("ful_url/get_no?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
});
I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.