Refresh body of bootstrap modal dialog after uploading something - javascript

I'm creating a service where I'm changing some data in DB via bootstrap modal dialog. After uploading file I'm showing name of this in my modal dialog body. But I can not see the name of the file what I've just uploaded, I have to close dialog and then open it again, without it I'm not able to see the actual name of uploaded file.
The question is: How to refresh "modal-body" of modal dialog without closing it?
Here is my modal html:
<div class="modal fade" id="editModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="width: 535px">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="dialog-edit"></div>
<div id="EditStatus"></div>
</div>
</div>
</div>
and my javascript:
tab.on("click", ".btnUpload", function (e) {
var formData = new FormData();
var id = $(this).closest("tr").find('#fileId').text();
var file = document.getElementById("FileUpload").files[0];
formData.append("id", id);
formData.append("file", file);
$.ajax({
type: "POST",
url: "/Events/UpdateJsionFile",
contentType: false,
processData: false,
dataType: "JSON",
data: formData,
success: function (data) {
if (!data.success) {
var res = $('<div style="color:red;">' + data.error + '</div>')
$('#uploadStatus').html(res);
}
else {
$('#uploadStatus').html("File #1 uploaded!");
}
}
});
});
Everything is working perfect but I have no idea how to refresh data after uploading?
Can somebody help me with it?

I've solved it like this:
first I've created a variable with file name:
var fileName = document.getElementById("FileUpload").files(0).name;
and then, after success in my ajax:
$('.FileUpload').html(fileName);
hope it will help somebody, who was looking for the same thing...

Related

Jquery append function only works on initial ajax request, requires page refresh to repopulate another div

I am making an AJAX request to get an JSON array, upon success another AJAX request is performed and the contents are populated to the div of a bootstrap modal via jquery append function. Everything works correctly for the first selection, however, once I close the modal and attempt another entry the append function no longer populates the div. I attempted to empty the contents of the div and also tried the clone function but no matter what the contents are not repopulated until a page refresh. I tried logging to the console and the data is correct and repopulated with each click. Sorry if my code is terrible, still learning. Below is the code I am using. Any help would be appreciated.
function makeModal({first_name, last_name, id}) {
return `
<div class="modal fade" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">${first_name} ${last_name}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>${last_name}</p>
<p>${id}</p>
<p id="job_history"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>`;
}
//onclick event
$(document).on('click', '.applicant_detail', function(e) {
var id = $(this).data('id');
//$('#job_history').empty();
$('#myModal').modal('dispose');
$.ajax({
type: "POST",
url: "/admin/get_applicant",
dataType: 'json',
data: {id:id},
success: function(data) {
var count = Object.keys(data).length;
$.each(data, function(index, element) {
var m1 = $(makeModal({last_name:element.last_name, first_name:element.first_name, id:element.id}));
document.body.insertAdjacentHTML('beforeend', m1);
m1.modal('show');
});
$.ajax({
type: "POST",
url: "/admin/get_job_history",
dataType: 'json',
data: {application_id:id},
success: function(data) {
var count = Object.keys(data).length;
$.each(data, function(index, element) {
$('#job_history').append("Job Title: " + element.job_title + '<br>').clone();
console.log('Job Title: ' + element.job_title);
});
},
});
},
});
});
I figure it out. I needed to destroy the modal created via my makeModal function. So I removed the div with each click event. Not sure if this is the best way but it works.
$('#myModal').remove(); //added this below the click event

Passing variables to a bootstrap modal

I'm building a web application based on Dark Sky API which gets the forecast about a location. I would like to show the data I have collected from the API in a bootstrap modal but I don't know how to pass the javascript global variables that I have defined for temperature, humidity, etc...
I'm gonna display here the function where I get the data from the API:
function temperature() {
jQuery(document).ready(function ($) {
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/{mykey}" + latMark + "," + lngMark + "?units=ca",
dataType: "json",
async: false,
success: function (parsed_json) {
temperature = Math.round(parsed_json.currently.temperature);
summary = parsed_json.currently.summary;
humidity = parsed_json.currently.humidity * 100;
icon = parsed_json.currently.icon;
},
error: function (parsed_json) {
console.log("Error adding the temperature.");
}
});
});
And this is my modal right now which is based in a template I got from bootstrap but will help you answer this question
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Weather Information</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<p id="output"></p><br>
<canvas id="icons" class="icon" width="128" height="128"></canvas>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I was looking to do something in the body of the modal like the following example:
The temperature is: + variable + ºC;
The humidity is: + variable*100 + %;
The summary is: + variable;
Thanks in advance for the help :D
Append the variables content to output id on ajax success, it will render the variables into HTML.
Also, jQuery append supports the HTML, you can add according to your wish. more details see here.
function temperature() {
$.ajax({
url:
"https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/{mykey}" +
latMark +
"," +
lngMark +
"?units=ca",
dataType: "json",
async: false,
success: function(parsed_json) {
temperature = Math.round(parsed_json.currently.temperature);
summary = parsed_json.currently.summary;
humidity = parsed_json.currently.humidity * 100;
icon = parsed_json.currently.icon;
jQuery("#output").append("The temperature is: " + variable + "ºC");
jQuery("#output").append("The humidity is:: " + humidity + "%");
jQuery("#output").append("The summary is: " + summary);
},
error: function(parsed_json) {
console.log("Error adding the temperature.");
}
});
}```

Alert Box to show when error occur

I am looking to implement the bootstrap alert boxes, for when I have a concurrency error on a page. Currently this is how the Controller is setup:
I would do something like this with sweetalert2:
https://jsfiddle.net/x07g89h9/
or with bootstrap
https://jsfiddle.net/mmq27s86/2/
HTML
declare bootstrap modal
<div id="myModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Errors</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul id="errors">
</ul>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary">Close</button>
</div>
</div>
</div>
</div>
JS
function showModal(errors){
var $msg = $("#errors");
$msg.empty();
for(var i=0; i<result.errors.length; i++){
$msg.append("<li>" + errors[i] + "</li>");
}
$('#myModal').modal();
}
$.ajax({
url: 'any...',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
// in case of error
if(result.ChangeStatus !== "Success"){
showModal(result.errors);
}
},
error: function () {
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
}
});
});
Check this or this.
Articles are too long to report whole code here.

Using a button to open a page containing details of a stock item

My intention is to show products on the index page with links. When the link is clicked a 'modal' page opend showing the details of that product.
I have a button that links to a product page, but not the other items on the index page.
How do I use this link to open each product page?
The code for button:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#details-1">Details</button>
The modal:
<?php
include 'details-modal-item01.php';
include 'details-modal-item02.php';
?>
The page details-modal-item01.php is more or less a template for the other items:
<div id="item01" class="modal fade item01" tableindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true"> -- rest of code goes here --</div>
Any help will be appreciated.
Instead of all the include jazz, which will become unmanageable once you got many products you should use ajax to load the content/partial or build from json into the modal-content section.
Ok easy said then done, so here is an example.
This is genrally how I do it, by using ajax and partials.
The Link(s), you would need to change the data-url="" attribute to point to your partial.
<i class="fa fa-plus fa-fw"></i> Open Modal
The modal wrapper. This would be placed at the bottom of your template, before </body>.
<div id="ajax-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Loading...</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close">×</button>
</div>
<div class="modal-body slow-warning"><p>Please wait...</p></div>
</div>
</div>
</div>
The partial, would be served from the links endpoint, you could check the request is ajax and show the partial and if its not show a full page instead.
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Foo Bar</h4>
</div>
<div class="modal-body"></div>
</div>
Then the jquery, which handles loading the content into the modal.
<script>
var ajax_modal = function(e) {
e.preventDefault();
$('#ajax-modal').modal('show');
var modal = '.modal-content';
var default_content = '' +
'<div class="modal-header">' +
' <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button>' +
' <h4 class="modal-title">' +
' Loading...' +
' </h4>' +
'</div>' +
'<div class="modal-body">' +
' <p class="slow-warning">Please wait...</p>' +
'</div>';
$(modal).html(default_content);
setTimeout(function() {
if ($(document).find('.slow-warning').length > 0) {
$(document).find('.slow-warning').html('Content failed to load, please refresh your browser and try again.');
}
}, 5000);
//
var dialog_size = $(this).data('size');
if (dialog_size == 'modal-lg') {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-lg');
}
else if (dialog_size == 'modal-sm') {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-sm');
}
else {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-md');
}
//
var request = $.ajax({
url: $(this).data('url'),
method: "GET",
dataType: "html",
cache: false
});
request.done(function(data) {
$(modal).replaceWith($('<div />').html(data).find(modal)[0]);
});
request.fail(function(jqXHR, textStatus) {
console.log('modal failed to load', textStatus);
});
};
$(document).find('.ajax-modal').off('click').on('click', ajax_modal);
</script>

How to use javascript to trigger a modal one after another

I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};

Categories