How to trigger Alert after Server Error Response with Dropzone.js - javascript

I want to trigger a javascript alert from dropzone.js when the server returns an error. (in json).
Here is my function/method. It seems to be working fine.
public function file_upload($account_id,$bid_id) {
$path = FMREPO . "/account-" . $account_id . "/bid-project-" .$bid_id . "/";
if (file_exists ( $path )){
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$targetPath = $path . "diagram-" . $bid_id . "-";
$targetFile = $targetPath . $fileName ;
move_uploaded_file($tempFile, $targetFile);
// $this->load->database(); // load database
// $this->db->insert('file_table',array('file_name' => $fileName));
}
} else{
header('HTTP/1.1 500 Internal Server Directory Not Found');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('error' => 'File Could Not Be Saved')));
}
}
Here is my Dropzone options. This is the part I don't know how to do or make it work. The "error:" is what I added but it always triggers an alert, even when the file upload was successfull. What do I need to do here?
Dropzone.options.diagramDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 6, // MB
maxFiles: 2,
thumbnailWidth: 100,
thumbnailHeight: 100,
error: function(){
alert('error');
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
console.log(file);
this.removeFile(file);
});
}
}
Edit: I just realized this
error: function(){
//alert here
},
should be
error: function(response){
//alert here
},
so now that is working! But the with alert(response) I get [object]. So now the question is how do I alert my string?

You can set up you alert inside the init option like this:
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
console.log(file);
this.removeFile(file);
}),
this.on("error", function(file, errorMessage, xhr) {
alert(errorMessage);
])
}

Related

Symfony 4.4 - Summernote editor upload base64 images to server

Pretty common problem with a lot of answers here but couldn't make it work for my Symfony 4 application. I tried to debug my action with dump() and die(), it doesn't even enter the action and I think that's why my images won't upload.
My JavaScript code in Twig:
<script>
var url = "{{ path('editor_file_upload') }}";
$(document).ready(function() {
$('.summernote').summernote({
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
let formData = new FormData();
formData.append("file", file);
$.ajax({
data: formData,
type: "POST",
url: url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
My Controller action:
/**
* #Route("/editor-file-upload", name="editor_file_upload")
*/
public function uploadEditorFile(Request $request)
{
/** #var UploadedFile $File */
$File = $request->files->get('file');
if ($File) {
$originalFilename = pathinfo($File->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $File->guessExtension();
try {
$File->move(
$this->getParameter('editor_images'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
}
}
The problem was that I didn't return any response, here's the edit:
/**
* #Route("/upload-editor", name="admin_upload_editor")
*/
public function uploadEditorFile(Request $request, KernelInterface $kernel) {
/** #var UploadedFile $file */
$file = $request->files->get('img');
if (empty($file))
{
return new Response("No file",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();
try {
$file->move(
$kernel->getProjectDir() . '/' .
$this->getParameter('public_dir') . '/' .
$this->getParameter('editor_dir'),
$newFilename
);
return new Response("/editor_images/" . $newFilename, Response::HTTP_OK);
} catch (FileException $e) {
return new Response("Cannot upload file!",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
}
}

How to use ajax for request the WHMCS hooks function and get my required return data?

I read the WHMCS demo code for developing a provisioning module:
the frontend code, overview.tpl.
the backend code, provisioningmodule.php.
but my code follow by the upper I want to use ajax for request, so the whole page will not re-render.
My frontend ajax code:
jQuery.ajax({
url: url,
type: "POST",
data: {
...
qn_action: "bmc"
},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus){
console.log('ldl:',data) // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
jQuery('.powercontrol').removeClass('disabled');
jQuery(i_id).css('display', 'none');
jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
},
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})
in my backend PHP code:
function qidicatedserver_ClientArea(array $params)
{
// Determine the requested action and set service call parameters based on
// the action.
$qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';
$tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';
$bmc_action = "";
$server_name = "";
$templateFile = 'templates/overview.tpl';
$bmc_result = "";
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
"status"=>200,
"data"=>"my test return data"
)
);
return $resp;
}
try {
// Call the service's function based on the request action, using the
// values provided by WHMCS in `$params`.
return array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
'data' => array(
"status"=>"200",
"data" => array(
"bmc_result" => null
)
),
),
);
} catch (Exception $e) {
//echo $e;
// Record the error in WHMCS's module log.
logModuleCall(
'qidedicatedserver',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
// In an error condition, display an error page.
return array(
'tabOverviewReplacementTemplate' => 'templates/error.tpl',
'templateVariables' => array(
'usefulErrorHelper' => $e->getMessage(),
),
);
}
}
when the ajax request executed, there will get error, execute the below code:
console.log('error: '+jqXHR.responseText); // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg); // the console log: `Error msg: Error: Parsing JSON Request failed.`
So, there must be issue in there, my problem is how to use ajax for HTTP request in WHMCS custom provisioning module, but I try get failed like upper. (I tried use form request PHP, there can get correct data, but there will re-fresh the whole page, its not my desired, I don't what the page to be refresh)
Who can tell me how to use ajax for request WHMCS hook function and return correct data as my wish?
You can find more introduction of WHMCS provisioningmodulethere.
EDIT-01
I tried change the return PHP code like this:
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => json_encode(array(
"status"=>200,
"data"=>"dasdas"
))
);
return $resp;
}
but still this error.
Put your Ajax/PHP code in separated file, not in _ClientArea method, suppose your module called 'mail_service', then create a file in:
\modules\servers\mail_service\for_json.php
for_json.php
<?php
#define("ADMINAREA", true);
define("CLIENTAREA", true);
#define("SHOPPING_CART", true);
require_once(__DIR__ . '/../../../init.php');
require_once(ROOTDIR . '/includes/dbfunctions.php');
#require(ROOTDIR . "/includes/orderfunctions.php");
#require(ROOTDIR . "/includes/domainfunctions.php");
#require(ROOTDIR . "/includes/configoptionsfunctions.php");
#require(ROOTDIR . "/includes/customfieldfunctions.php");
#require(ROOTDIR . "/includes/clientfunctions.php");
#require(ROOTDIR . "/includes/invoicefunctions.php");
#require(ROOTDIR . "/includes/processinvoices.php");
#require(ROOTDIR . "/includes/gatewayfunctions.php");
#require(ROOTDIR . "/includes/modulefunctions.php");
#require(ROOTDIR . "/includes/ccfunctions.php");
#require(ROOTDIR . "/includes/cartfunctions.php");
#include_once(ROOTDIR . '/includes/clientareafunctions.php');
#use WHMCS\ClientArea;
#use WHMCS\Database\Capsule;
#use WHMCS\Smarty ;
file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
{
// do your job
//header('Content-type: application/json; charset=utf-8');
header("Content-Type: application/json", true);
header('HTTP/1.0 200 OK');
echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
}
?>
and use the follwing JS code:
jQuery.ajax({
url: "/modules/servers/mail_service/for_json.php",
type: 'POST',
data: {qn_action: 'bmc'},
cache: false,
dataType: 'json',
success: function (data, textStatus){console.log('ldl:',data)},
error: function(jqXHR, e){
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})

summernote 0.8.8 onimageupload example

Does anyone have a good example of the code to use Summernote 0.8.8 that uploads images to a directory on the server (not as base64)? I tried some of the older posted results(they might have worked with older versions of Summernote),but nothing seams to work for me. I'm not strong on Java, so I'm not sure how to fix the issue.
Summernote's web example is
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
$summernote.summernote('insertNode', imgNode);
}
}
});
$('#summernote').on('summernote.image.upload', function(we, files) {
$summernote.summernote('insertNode', imgNode);
});
But this does not work, as the image does not 'upload' it is still in Base64. This does work for me, as it loads too slow. Thanks!
FOR SUMMERNOTE 0.88+
I Tested it with these CDN
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.min.js"></script>
JAVASCRIPT
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: "300px",
dialogsInBody: true,
callbacks: {
onImageUpload: function(files) {
uploadFile(files[0]);
}
}
});
});
function uploadFile(file) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: "upload_url_path", //replace with your url
cache: false,
contentType: false,
processData: false,
success: function(url) {
$('#summernote').summernote("insertImage", url);
}
});
}
</script>
PHP SAMPLE CODE FOR UPLOAD
<?php
$allowed = array( 'png', 'jpg', 'gif' );
if( isset($_FILES['file']) && $_FILES['file']['error'] == 0 ) {
$extension = pathinfo( $_FILES['file']['name'], PATHINFO_EXTENSION );
if( !in_array( strtolower( $extension ), $allowed ) ) {
echo 'AN ERROR OCCURED - INVALID IMAGE';
exit;
}
if( move_uploaded_file( $_FILES['file']['tmp_name'], 'assets/images/'.$_FILES['file']['name'] ) ) {
echo base_url().'assets/images/'.$_FILES['file']['name']; // echo absolute file_url
exit;
}
}
echo 'AN ERROR OCCURED';
exit;
?>
https://summernote.org/deep-dive/#onimageupload

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

Categories

Resources