Dropzone configure for delete option - javascript

I have added below code of dropzone
<html>
<head>
<!-- 1 -->
<link href="dropzone.css" type="text/css" rel="stylesheet" />
<!-- 2 -->
<script src="dropzone.js"></script>>
</head>
<body>
<!-- 3 -->
<form action="upload.php" class="dropzone"></form>
</body>
</html>
And it works fine.
But I am wondering how do I add delete button for deleting particular file from server.

First you must add to dropzone configuration the option addRemoveLinks: true
Then we listen to event for when a file is removed and the do an Ajax call to delete it from server (in here I just send the file name) and on in there just do the codebehind deleting a file.
Dropzone.autoDiscover = false;
myDropzone = new Dropzone("#DzUpload", {
url: 'upload.php',
addRemoveLinks: true, //This will show remove button
});
//Init Dropzone
myDropzone.on("removedfile", function (file) {
if (!file.name) { return; } // The file hasn't been uploaded
$.ajax({
type: 'POST',
url: 'delete.php',
dataType: "json",
data: { FileName: file.name },
success: function (result) {
console.log("deleted")
}
});
});

Related

Ajax jQuery doesn't redirect to the url with Laravel

I'm new to Ajax, but I was able to make a form where I write data -> submit and the controller does it's job.
My problem is that I wanted to make a delete button for the records, but it doesn't work, just reloads the page, the route is fine, the alert works fine and the token is fine too.
Here is the code:
The route
Route::post('/delete/{testTaker}', [TestTakerController::class, 'delete']);
The button
<form id="delete">
{{ csrf_field() }}
<button class="deletett" data-id="{{ $testTaker->testTaker }}">delete</button>
</form>
The js part:
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$(".deletett").click(function(){
var testTaker = $(this).data("id");
alert(testTaker);
jQuery.ajax({
url: "/delete/" + testTaker,
method: 'post',
data: {
name: testTaker
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}});
});
</script>

Show loader only after file is selected and hide when cancel or cross button clicked

I have been trying to show loader when file uploaded using single input element and no other element involved, but its not working.
<!-- ! ajaxLoader Begin -->
<div class="ajaxLoader" id="Loader">
<img src="~/assets/img/loader.gif" alt="">
</div>
<!-- ! ajaxLoader End -->
<input asp-for="File" id="File" type="file" class="form-control DocumentFile" accept=".pdf" title="Browse From Folder" />
Below is the javascript:
<script>
$('#File').focus(function (evt) {
$(this).change(
function () {
$('.ajaxLoader').show();
if ($(this).length === 0) {
$('.ajaxLoader').hide();
}
else{
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '#Url.Action("UpdatedDocumentFile", "Document")',
data: formData,
async: false,
processData: false,
contentType: false,
success: function(res) {
// Do some process on 'res'
$('.ajaxLoader').hide();
},
error: function(e) {
$('.ajaxLoader').hide();
}
});
}
}
);
});
</script>
It in anyway ,does not show the loader on file upload.
Although I tried using below link :
Loader while file upload
but it starts loader as soon as the input element is clicked and closes on any actions of File Upload(Upload, Cancel, Cross button click), whereas in my case it calls ajax and do some processing to finally upload file to server.
Also, I have tried with change event of input file but it does not work if I open the File Location but cancels on first attempt, it never closes the loader for first trial
How can show/Hide loader in case of File Upload, Cancel or Cross button click event?
you can use focusout, but i would prefer on click with a button, but you can also use
change
and there is beforesend in ajax, where you can start your loader
$('#File').on('change', function (evt) { // or use focusout
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '#Url.Action("UpdatedDocumentFile", "Document")',
data: formData,
async: false,
processData: false,
contentType: false,
beforeSend: function ()
{
$('.ajaxLoader').show();
},
error: function (e) {
$('.ajaxLoader').hide();
},
success: function (res) {
$('.ajaxLoader').hide();
}
});
});
or you can set a defaukt setting for all ajaxs, try this , then you don't need loader in ajax
var $loader = $('#Loader'), timer;
$loader.hide()
.ajaxStart(function()
{
timer && clearTimeout(timer);
timer = setTimeout(function()
{
$loader.show();
},
1000);
})
.ajaxStop(function()
{
clearTimeout(timer);
$loader.hide();
});

Uploading a file with JavaScript/Ajax to SpringBoot endpoint

I am new to front-end development and am having troubles piecing together a solution for this specific form setup.
I have an already created jsp representing this instance creation page. It's a form containing numerous drop downs and check boxes. I need to add a file upload option to it.
The jsp is set up like this...
<form class="form-horizontal" id="editInstanceForm" onsubmit="return false;"> ....
Here's my input field
<div class="form-group" id="uploadForm">
<label class="col-xs-4 control-label instanceDefaultLabel" for="fileSearchField">Default Location and Zoom:</label>
<div class="col-xs-3">
<input name="myFile" type="file" id="fileSearchField" multiple=false>
<button id="upload-button">Upload</button>
</div>
.....
</div>
Now I have an ajax call that I was originally wanting to use before I realized that the whole form is attempting to submit when I uploaded the file. Here it is...
$('#upload-button').click( 'click',
function() {
var form = $('#fileSearchField')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/edit/uploadfile",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert("hi stuff worked");
},
error: function (e) {
alert("nope!");
}
});
}
);
I got this suggestion in researching how to upload a file with jQuery/ajax and Spring Boot (I am using Spring Boot to create my endpoint). Here are some articles that I have been reading in an attempt to understand how to do this...
https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/
http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-ajax-multipartfile-application-downloadupload-files-springboot-jquery-ajax-bootstrap#3_Implement_upload_controller
and many more. This seemed like the solution until I realized this was a form and I think I need to save all the fields at once. This is going to mean that I have to modify the already created ajax function that saves this form and passes it to the end point. Now I don't know how to get my MulitpartFile in as part of this different function. The existing one is like this...
$.ajax({
type: "POST",
url: webroot + "/viewerConfig/mapInstance/insertOrUpdate",
data: JSON.stringify(instanceData),
processData: false,
contentType: 'application/json',
success: function (data) {
if (data.status === "OK") {
alert("Instance created/updated successfully");
} else {
alert("Unknown error");
}
},
fail: function () {
alert("Unknown error");
},
error: function (a) {
alert("Unknown error");
}
});
});
This is exactly where I am stuck and I need to be pointed in the correct and productive direction.
I don't know if this will help but here's my end point that looks like the one I have to hit with my file param added...
#RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody BaseStatusResponse insertOrUpdate(final #RequestBody SaveAdminInstanceView newInstance, HttpServletResponse servletResponse,
#RequestParam MultipartFile file)
EDIT:
I have done some curl troubleshooting and it's the MulitpartFile that's failing. I am passing it as suggested yet I am getting this exception:
org.springframework.web.multipart.MultipartException: The current request is not a multipart request</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
You can try below code:
$.ajax({
url: "/edit/uploadfile",
type: 'POST',
data: new FormData($(this)[0]),
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
cache: false,
success: function(res) {
console.log(res);
},
error: function(res) {
console.log('ERR: ' + res);
}
});
And in controller, you needn't declare consumes = "application/json"
I figured out what I was doing wrong. It wants the form element not the file one. FormData needs the Form. Thanks for your help though! :)
There you have 3 diferent ways to do this with spring-boot at 2022 be sure the file size is lower than the server maximun file size.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="http://192.168.12.168:8081/uploadfile" enctype="multipart/form-data">
<input type="file" id="fileinput" name="file" /><br/><br/>
<input type="submit" value="Submit using HTML" />
</form>
<button onclick="submitStyle1()">Submit using FETCH</button>
<button onclick="submitStyle2()">Submit using XHR</button>
</body>
<script>
function submitStyle1(){
const photo = document.getElementById("fileinput").files[0];
const formData = new FormData();
formData.append("file", photo);
fetch('http://192.168.12.168:8081/uploadfile', {method: "POST", body: formData});
}
function submitStyle2(){
const photo = document.getElementById("fileinput").files[0]; // file from input
const req = new XMLHttpRequest();
const formData = new FormData();
formData.append("file", photo);
req.open("POST", 'http://192.168.12.168:8081/uploadfile');
req.send(formData);
}
</script>
</html>
To see an example type me at https://github.com/JmJDrWrk

Implementing Microsoft's Project Oxford - Emotion API and file upload

I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!
I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>

jQuery AJAX Loading Page Content Only After I Press Shift Key

My ajax + jquery loading page only after holding shift key and duplicate new empty window.
If I press the loading button nothing hapen, only after I press shift key I get to load the page correctly...
this is my ajax script:
$(document).ready(function () {
$(".getUsersA").click(function () {
$.ajax({
beforeSend: function () {
$(".gridD").html(spinner)
},
url: 'lib/some_url.php',
type: 'POST',
data: ({
data1:'2013-09-01'
}),
success: function (results)
{$(".gridD").html(results);}
});
});
});
I have a second js file with just this line of code for spinner
var spinner = "<img src='images/spinner.gif' border='0'>";
html code:
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/general.js"></script>
</head>
<body>
<h1>Putting it all tugether ... with jQuery</h1>
<div class="thedivD">Get Users</div>
<h3>jQuery results</h3>
<div class="gridD"></div>
</body>
</html>
Try to change
<a href="" ...
to
<a href="#" ...
in your HTML... a blank href is a link to this same url, so a click on the button forces also a page reload...
data: [{
data1:'2013-09-01'
}]
try It.
If you can not post the data1 or success not coming.
$.ajax({
beforeSend: function () {
$(".gridD").html(spinner)
},
url: 'lib/some_url.php',
type: 'POST',
data: [{
"data1":'2013-09-01'
}],
success: function (results)
{$(".gridD").html(results);}
});
?

Categories

Resources