How to popup form after file upload - javascript

File upload button on one file and popup form in another file("/uploadFile").
I want to popup form after upload file submit/on "ok" click.
This is my first file index.html where I have list that have upload file button:
<li><a href="/uploadFile"><input type="file" id="hiddenUploadField" style="display: none;" accept=".dxf, .dwg"
class="upload" data-toggle="modal" data-target="#importData">
<label for="hiddenUploadField"><i class="fas fa-folder-open"></i> <span>Import</span></label></a>
</li>
At the end of file I use this code for popup modal:
<div class="modal fade text-center" id="importData" >
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
The code to trigger the popup is:
$('#hiddenUploadField').change(function (e) {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
$('#importData').modal('show').find('.modal-content').load($(this).attr('href'));
});
}
The problem is when I click "ok" on the file window, it does not show up the modal popup box. It just fades the background and does nothing.

Your code to show the modal is need to inside the change function, like this
$('#hiddenUploadField').change(function (e) {
// your code goes here for the modal.
$('#importData').modal('show').find('.modal-content').load($(this).attr('href')); }
});

Related

How to set null image file after ajax success in PHP?

I am working on ajax and PHP.
When I click on the post button the message value removes by $("#message").val(""); after ajax success (data inserted into the database by PHP and ajax ) but the file(browse ), the image doesn't remove after success. The file should be empty after AJAX success and the ajax code is not run if I leave the image. I want to leave an image and the message should be inserted without an image and with the image is working.
$(document).on("click", "#save", function (e) {
e.preventDefault();
var form_data = new FormData();
form_data.append('message', message)
var property = document.getElementById('photo').files;
property = property[0];
if(property){//you have to check if the files exists or it will fail trying to access properties from an undefined object
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file",property);
}
//Ajax call to send data to the insert.php
$.ajax({
type: "POST",
url: "insert_posts.php",
data: form_data,
contentType:false,
cache:false,
processData:false,
success: function (data) {
//Insert data before the message wrap div
$(data).insertBefore(".message-wrap:first");
//Clear the textarea message
$("#message").val("");
$("#form")[0].reset();
$('#preview').attr('src', "#");
$("#photo").val("");
}
});
});
The post button doesn't work when I leave the image file.
but when I leave the text blank and select the image from the computer then the post button works.
I want the post button should be work when I leave the browse file.
And After ajax success, the file browse should be empty.
<div class="c-header">
<div class="c-h-inner">
<ul>
<li><input type="file" onchange="readURL(this);" style="display:none;" name="photo" id="photo"></li>
<li><img src="assets/icon/icon1.png"></img>Add Photo</li>
</ul>
</div>
</div>
<div class="c-body">
<div class="body-left">
<div class="img-box">
<img src="<?php echo 'assets/images/'.$image;?>"></img>
</div>
</div>
<div class="body-right">
<textarea class="text-type" name="message" id="message"
placeholder="What's on your mind?"></textarea>
</div>
<div id="body-bottom">
<img src="#" id="preview"/>
</div>
</div>
<div class="c-footer">
<div class="right-box">
<ul>
<li><input type="submit" name="save" id="save" value="Post" class="btn2"/></li>
</ul>
<br>
</div>
I am using js to show image preview.
ew
<script type="text/javascript">
//Image Preview Function
$("#uploadTrigger").click(function(){
$("#photo").click();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#body-bottom').show();
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
The image preview should be clear or remove after ajax success and post button should be work when i leave image to browse .
The file input should reset however you need to remove the preview image like:
var form_data = new FormData();
form_data.append('message', message)
var property = document.getElementById('photo').files;
property = property[0];
if(property){//you have to check if the files exists or it will fail trying to access properties from an undefined object
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file",property);
}
success: function (data) {
//Insert data before the message wrap div
$(data).insertBefore(".message-wrap:first");
//Clear the textarea message
$("#message").val("");
$("#form")[0].reset();
$('#preview').attr('src', "#");//Reset the preview to the original state
}
If the file input is not resetting try to add $("#photo").val(""); inside the success function.

Hide a card after confirming in bootstrap modal on AJAX success

My delete page contains multiple post with delete button, when delete button is pressed bootstrap bootstrap modal opens and will ask for confirmation are you sure you want to delete post ? YES : NO
when YES button is pressed .click(function (e){....} sends AJAX request to database, if ajax return success that paticular card should be hidden
so i tried with following code
$(document).ready(function () {
$("#confirm").click(function (e) {
e.preventDefault();
var that = this;
const act = $(this).attr('data-act');
const para = $(this).attr('data-para');
const hash = $(this).attr('data-hash');
$.ajax({
url: '/include/ajax/mark_sold.php', // Call delete.php to update the database
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
$(that).closest('div.card').hide(); //to hide div after ajax success
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
return false;
});
HTML
<div class="card border-0 small col-lg-3 col-md-2 col-6 mb-2 px-1">
<img class="card-img-top rounded-0" src="/upload/" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">title</h6>
</div>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-sm modalopen" data-hash="6d8ce77d206011027297b693be999704" data-para="A4IxzuRP8ATv">delete</button>
</div>
How do i hide card after confirming in modal
The problem in your code is, that your variable "that" is not referring to the delete button, but to the confirm button of the dialog, therefore you can't use closest() function. At this point, you should use some specific identification for your card/delete button. For example:
$('button[data-hash="'+hash+'"]') .closest('div.card').hide();
Another point that I don't see in your code is the transfer of data variables (act, para, hash) to the dialog confirm button. For example your code $(this).attr('data-hash') can't reach value from the delete button because $(this) refers to the dialog confirm button. The solution to this problem is to pass a unique identifier to the dialog button.
$(".deleteBtn").on('click',function(){ //Add on click event to all delete buttons
$("#confirm").data("hash",$(this).data("hash")); //Pass hash value to dialog confirm button
});
$("#confirm").click(function (e) {
e.preventDefault();
var delBtn = $('button[data-hash="'+$(this).data("hash")+'"]'); //Get specific delete button element by passed hash value
const act = delBtn.attr('data-act'); //Get data variables from the delete button element
const para = delBtn.attr('data-para');
const hash = $(this).data("hash");
$.ajax({
url: '/include/ajax/mark_sold.php',
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
delBtn.closest('div.card').hide(); //Find closest .card element to the specified delete button
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
Don't forget to add .deleteBtn class to your delete buttons.
Hope it helps.

How to refresh content of iframe from controller in ASP.NET MVC?

I have a question about combination of asp.net mvc and iframe.
I'm trying to edit retrieved data from db on iframe.
The problem is that when the page firstly loads the parent contents, iframe contents is also loaded and can't be edited later.
public ActionResult StudentDetail(string id)
{
Student student_data = null;
if (id != null)
{
student_data = getId(id);
}
else
{
return null;
}
return PartialView("StudentDetail",student_data);
}
As you can see above code,if any ID is selected by hyperlink of view,
it returns partial view for iframe.When it comes to this page at the first time,
becuase any Id isn't selected,it returns null.
Below code is snippet of the parent view.This calls controller and content is set by null when it comes to loading this page at the first time.
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-content">
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="myFlame" class="embed-responsive-item" src="/Home/StudentDetail" frameborder="0" allowtransparency="false" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
After loading the parent page and iframe page, user push the hyperlink to pop up the iframe to edit data.The snippet of code is below,it calls javascript to send id to controller
<td>#student.id</td>
Code of javascript is below.
<script>
var TeamDetailPostBackURL = '/Home/StudentDetail';
$(function () {
$(".anchorDetail").click(function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myFlame').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
//$("#closebtn").on('click',function(){
// $('#myModal').modal('hide');
$("#closbtn").click(function () {
debugger;
$('#myModal').modal('hide');
});
});
</script>
After pushing a hyperlink,javascript send the data to controller and retrieve data from db and return partialView of StudentDetail.cshtml.but it still shows empty iframe.
How can I refresh the content of iframe?

Uploading files to django through ajax

I'm having trouble trying to upload files to django using ajax. The upload process is done in a modal.
Form
<div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel2">Upload File</h4>
</div>
<div class="modal-body">
<div class="modal-body">
{% crispy fileform %}
</div>
</div>
</div>
</div>
</div>
The modal toggle
<a data-toggle="modal" href="#fileUploadModal" data-id="0" role="button" class="btn btn-success btn-sm pull-right">
<i class="fa fa-fw fa-cloud-upload"></i>
Upload File
</a>
This is how my file upload looks like
$(document).ready(function(){
var file = 0;
$('#fileUploadModal').on('show.bs.modal', function(e) {
file = $(e.relatedTarget).data('id');
var form = $(e.currentTarget).find('form');
$.ajax({
url: "{% url 'employee:ajax-file-upload' %}",
type: "POST",
data: $(form).serialize() + '&action=load&eid=' + employee + '&fid=' + file,
success: function(data) {
if (data['form_html']) {
$(form).html(data['form_html']);
$('.datepicker').datetimepicker({
format: 'YYYY-MM-DD'
});
}
}
});
});
$(".container" ).on('click', '#submit-file-upload', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var form = $(this).closest('form');
$.ajax({
url: "{% url 'employee:ajax-file-upload' %}",
type: "POST",
data: $(form).serialize() + '&eid=' + employee + '&fid=' + file,
success: function(data) {
if (!(data['success'])) {
$(form).replaceWith(data['form_html']);
$('.datepicker').datetimepicker({
format: 'YYYY-MM-DD'
});
}
else {
location.reload();
}
}
});
});
});
And my view looks like this
#json_view
#login_required
def ajax_file_upload(request):
if request.method == 'POST':
action = request.POST.get('action')
fid = int(request.POST.get('fid'))
eid = int(request.POST.get('eid'))
employee = Employee.objects.get(id=eid)
if action == 'load':
try:
file = File.objects.get(id=fid)
form = FileForm(instance=file)
except:
form = FileForm()
context = {}
context.update(csrf(request))
form_html = render_crispy_form(form, context=context)
return {'success': True, 'form_html': form_html}
else:
if fid == 0:
form = FileForm(request.POST or None, request.FILES or None)
else:
file = File.objects.get(id=fid)
form = FileForm(request.POST or None, request.FILES or None, instance=file)
if form.is_valid():
file = form.save(commit=False)
file.employee = employee
file.save()
messages.add_message(request, messages.SUCCESS, 'File was successfully saved.')
return {'success': True}
context = {}
context.update(csrf(request))
form_html = render_crispy_form(form, context=context)
return {'success': False, 'form_html': form_html}
I really can't seem to get it to work. I can successfully get other data but not the file. When I click on submit, it refreshes and I get a 'This field is required' in the file upload section.
I hope you can help me with this. Thanks.
Your ajax call is only posting the form data, not the file:
data: $(form).serialize() + '&action=load&eid=' + employee + '&fid=' + file
I would suggest using a library (such as jquery.fileupload.js but there's plenty of other options) to upload correctly a file, as it's quite a complex operation: you have to set the multipart/related body format, attach the file to your request as application/octet-stream, if it's large cut it into chunks etc etc...
With jquery.fileupload for example, uploading the file is as simple as:
$(function() {$('#fileupload').fileupload({
dataType: 'json',
formData: $(form).serialize()...
done: function(e, data) {
... your success handling code ...
}
});});
where $('#fileupload') targets your file input field (<input type='file'>).
The django code looks fine at first glance.

How to show Ajax response as modal popup

I have a link on clicking it is sending ajax request and getting response successfully which is html file and I am appending to a div, but I need to show that div as modal popup and I tried something below.
in html file
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
<div id="login_for_review" data-toggle="modal" data-target="#reviewLoginModal"></div>
in js file
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');// I tried to show this response as modal popup
},
error: function(output){
alert("fail");
}
});
});
output file
<div class="centerForm modal fade" role="dialog" style="margin-left: 35%;" id="reviewLoginModal">
<div class="modal-dialog modal-sm" >
<div class="modal-content">
// here I have login form
</div>
</div>
but I am not getting this html output as modal pup instead I am getting black screen can anyone help me how to do this?
In Bootsrap modal popup, You can use plain way to show modal which don't need pre-defined modal div container . see at modal
For E.g
$.ajax({
url: "url",
type: 'POST',
dataType: "html",
data:{id:params},
success: function(data, status, xhr) {
if(data==""){
window.location.href="/";
}
else{
BootstrapDialog.show({
title: "Modal Tital",
message: function(dialogRef){
$mydata = $($.parseHTML(data));
return $mydata;
},
onshow: function(dialog){
// and css change if need, eg.
dialog.$modalHeader.css("float","none");
},
onshown:function(dialog)
{
// event after shown
},
onhide:function(dailog)
{
// event on hide
}
});
}
},
statusCode: {
401: function () {
alert("Your session has been expired");
}
}
});
I solved this problem by creating modal and by removing data-toggle and data-target and just appending response to that modal div
Code For modal div
<div id="login_for_review" class="modal hide" role="dialog">
</div>
Code For hyperlink
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
Code For ajax call
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');//now its working
},
error: function(output){
alert("fail");
}
});
});

Categories

Resources