Convert html to Image and Download - javascript

I would like to convert every message that is received into an image, and with the download button download it. every post is different
This is my .js code
// fetch Messages
function fetchData() {
$('#displayMessages').html('<div class="alert alert-info">Stiamo recuperando i tuoi messaggi!...</div>');
$('#messages').click();
$.ajax({
url: 'controller/fetch_comments.php',
//success
success: function(data){
if (data=='please login') {
window.location='./';
console.log(data);
}
else{
var $fetch ='';
var component ='';
if (/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '#').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
data=JSON.parse(data);
console.log(data);
$.each(data, function(i, fetchAll){
var fetchData= data[i];
let message_title = fetchData.message_title ?? ""
$fetch += '<div class="row m-0"> <div class="pull-left alert col-md-2 mb-0"><img src="assets/img/anon.jpg" style=" width: 50px; height: 50px; border-radius:50%; box-shadow: 0 3px 2px rgba(0, 0, 0, 0.3); border: 5px solid #2c2c2c;" class="m-0"></div> <div class="alert col-md-7 m-0" style="margin-left:0px; color:#2c2c2c;"> <b>' +message_title +'</b><br>' +fetchData.description
+'</div> <div class="col-md-3 alert pull-right m-0"><span style="color: black;" class="fa fa-clock m-0"></span><br><text style="color: black; font-size:10px;"> ';
$fetch+=fetchData.date_created+'</text></div></div>';
});
} else {
$fetch +='<div class="alert alert-danger">Ancora nessun messaggio 😒</div>';
console.log(fetch);
$('#displayMessages').html($fetch)
}
$('#displayMessages').html($fetch);
}
}
});
}
this is the php code
$usersObj = new Comments();
$logsObj = new Logs();
$id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;
if (empty($id)) {
exit();
}
if ($allComments = $usersObj ->FETCH_COMMENTS($id)) {
$logDescription = 'data fetched!';
$logsObj->INSERT_LOG($id, $logDescription);
}else{
echo 'log failed';
}
echo isset($allComments) ? json_encode($allComments) : 'nothing found';
This is my html in my dashboard, is used to show the message
<div class="tab-pane active" id="home" role="tabpanel">
<div id="displayMessages">
</div>
</div>
I don't understand where I have to act, thanks for the help feel free to edit the code

You could do this as a oneliner in javascript.
Just by using the library html2canvas.
e.g.
html:
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
js:
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
put the image into an a tag with the propertie of "download".
I hope i could help you out.
EDIT:
In your html file add the cdn as following to the head:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas
/1.4.1/html2canvas.min.js"></script>
then in your js file
const body = document.querySelector("body");
const a_tag = document.createElement("a"); //just create an a tag
a_tag.innerHTML = "download"; //this text is displayed
a_tag.download = "image.png"; //pictures will download as image.png - you can customize the name and file format, but not all formats are acceptet in html2canvas
body.appendChild(a_tag); //append the a tag to the body element, you will need to customize this for your needs
html2canvas(document.querySelector(".wrapper")).then((canvas) => {
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob); //creates location of image
a_tag.href = url; //append url to a tags href
});
});
You will need this for every Message you receive. After your messages are displayed in the dom as html, the "html2canvas" will create an image out of that. In the "toBlob" function the image is just cached but not showing anywhere. We link the blob url (location of the cached image) to the a tags href. So if we then click on it, it will download. The .wrapper in the html2canvas function i've selected should be your message-div

Related

Html to MS Word using JS without Header and Footer

I am trying to convert HTML page into MS Word document file with help of below code.
My problem is I don't want any header and footer in it.
I want to create word file without header and footer extra spaces. Content should be sticky to the top.
I am getting the results but I don't want header and footer in it.
function Export2Doc(element, filename = ''){
var preHtml = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><title>Export HTML To Doc</title><style>body,html{margin-top: 0px !important;padding-top: 0px !important;padding-left: 0px !important;margin-left: 0px !important;font-size: 12px;margin-left: 0px !important;}.scheduledtxt{font-size: 14.5px;}table{margin: auto 0px !important;}</head><body>';
var postHtml="</body></html>";
var html = preHtml+document.getElementById(element).innerHTML+postHtml.trim();
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/msword;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = "test.doc";
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
<span id="exportContent">
<h2 style="text-align: center;">Test Document</h2>
</span>
<div style="text-align: center;">
<button id="hiddenBtn" style="background: royalblue; color: white;padding: 10px; border-radius: 10px;" onclick="Export2Doc('exportContent', 'word-content');">Export as .doc</button>
</div>
I have manage to achieve my goal with the following link
css print mode: display header and footer only on first page of a generated word doc
I just had to add below css code.
for better understanding just minify entire code and use when converting to the word file.
#page {
size: 2cm 2.7cmt;
margin: 0.4cm 0cm 0cm 0cm;
mso-page-orientation: portrait;
mso-header: none;
mso-footer: none;
}

Send an image with js and html into form

I had a code that looks like this https://cloth.ardive.id/Tshirt/index.html
I want to send the canvas as an image to a form where user need to fill some addon information (name, category) and in this form image from page before is have been displayed and user doesnt need to upload an image anymore. So when they submit the form, submited form is contains their filled information data with the image
because i want to send the canvas that wasnt an image, so we need to generates the canvas into image, then send it to the form.
this is how my form code lookslike (I'm using wordpress and woocommerce, but this code is html). what I want to is navigating into the form page with image already uploaded to this field
<script type="text/javascript">
wpuf_conditional_items.push();
</script>
</li><li class="wpuf-el featured_image" data-label="Gambar"> <div class="wpuf-label">
<label for="wpuf-featured_image">Gambar <span class="required">*</span></label>
</div>
<div class="wpuf-fields">
<div id="wpuf-featured_image-upload-container" style="position: relative;"><div class="wpuf-file-warning"></div>
<div class="wpuf-attachment-upload-filelist" data-type="file" data-required="yes">
<a id="wpuf-featured_image-pickfiles" data-form_id="4244" class="button file-selector wpuf_featured_image_4244" href="https://cloth.ardive.id/buat-produk/#" style="position: relative; z-index: 1;">Select Image</a>
<ul class="wpuf-attachment-list thumbnails">
</ul>
</div>
<div id="html5_1b67l1c6qtdqmec190711k33v46_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 0px; left: 0px; width: 106px; height: 29px; overflow: hidden; z-index: 0;"><input id="html5_1b67l1c6qtdqmec190711k33v46" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" accept="image/jpeg,.jpg,.jpeg,image/gif,.gif,image/png,.png,image/bmp,.bmp"></div></div><!-- .container -->
<span class="wpuf-help">Masukkan Gambar, gambar harus dengan resolusi tertinggi</span>
</div> <!-- .wpuf-fields -->
<script type="text/javascript">
jQuery(function($) {
new WPUF_Uploader('wpuf-featured_image-pickfiles', 'wpuf-featured_image-upload-container', 1, 'featured_image', 'jpg,jpeg,gif,png,bmp', 8000);
});
</script>
this is the code to save the image that have been already generated from the canvas to users desktop
the code is on canvas2image.js
// sends the generated file to the client
var saveFile = function(strData) {
document.location.href = strData;
}
var makeDataURI = function(strData, strMime) {
return "data:" + strMime + ";base64," + strData;
}
// generates a <img> object containing the imagedata
var makeImageObject = function(strSource) {
var oImgElement = document.createElement("img");
oImgElement.src = strSource;
return oImgElement;
}
var scaleCanvas = function(oCanvas, iWidth, iHeight) {
if (iWidth && iHeight) {
var oSaveCanvas = document.createElement("canvas");
oSaveCanvas.width = iWidth;
oSaveCanvas.height = iHeight;
oSaveCanvas.style.width = iWidth+"px";
oSaveCanvas.style.height = iHeight+"px";
var oSaveCtx = oSaveCanvas.getContext("2d");
oSaveCtx.drawImage(oCanvas, 0, 0, oCanvas.width, oCanvas.height, 0, 0, iWidth, iHeight);
return oSaveCanvas;
}
return oCanvas;
}
return {
saveAsPNG : function(oCanvas, bReturnImg, iWidth, iHeight) {
if (!bHasDataURL) {
return false;
}
var oScaledCanvas = scaleCanvas(oCanvas, iWidth, iHeight);
var strData = oScaledCanvas.toDataURL("image/png");
if (bReturnImg) {
return makeImageObject(strData);
} else {
saveFile(strData.replace("image/png", strDownloadMime));
}
return true;
}
this is another js to classed the function
//export options
$('.exportas').click(function(){
// get type to export
var to = $(this).data('type');
// alert(to);
// get our canvas
var oCanvas = document.getElementById("mycanvas");
// support variable
var bRes = false;
if(to == 'png'){
// export to png
bRes = Canvas2Image.saveAsPNG(oCanvas);
}
if(to == 'jpg'){
// maybe in some old browsers it works only on Firefox
bRes = Canvas2Image.saveAsJPEG(oCanvas);
}if(to == 'bmp'){
Res = Canvas2Image.saveAsBMP(oCanvas);
}
// if browser doesn't support mimetype alert user
if (!bRes) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
and on index.html, its look like this
<!-- export option (png, jpg, bmp) -->
<li>
<div class="btn-group dropup">
<a class="dropdown-toggle export btn" data-toggle="dropdown" href="#">
Export
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a href="#" class="exportas" data-type='png'>PNG</a>
<a href="#" class="exportas" data-type='jpg'>JPG</a>
<a href="#" class="exportas" data-type='bmp'>BMP</a>
</li>
so what i wanna ask you is, how to make a code to send the image to form (form is on another pages) with details i have been mentioned above. thanks

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

Pass info from text input through jquery in to php, which returns json, need to parse the return

I am getting a return of undefined. I don't even know what to do. So lost...
html
<!DOCTYPE html>
<html>
<head>
<!--Jquery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--Local files attached-->
<script type="text/javascript" src="CountryList.js"></script>
<link rel="stylesheet" type="text/css" href="CountryList.css" />
</head>
<body>
<div id="wrapper">
<!--Header-->
<h1>Country Information</h1>
<!--input box-->
<form>
<label for="countryInput">Input Country Name : </label>
<input type="text" id="countryInput"></input>
</form>
<br>
<br>
<!--Containing divs for lists-->
<div id="wrapper2">
<!--countries will load here-->
<div id="countryList">
Countries:
<div id="actualList">
</div>
</div>
<!--country info will load here-->
<div id="countryInfo">
Country Info:
<div id="actualInfo">
</div>
</div>
</div>
</div>
</body>
<div id="footer">
<!--Link to page-->
</div>
</html>
css
body{
margin-top:3%;
background-color:white;
text-align:center;
}
h1 {
}
h2 {
font-size:14pt;
}
#header {
color:white;
text-align:center;
padding:5px;
}
#footer {
color:white;
text-align:center;
padding:5px;
}
#countryList {
text-align:center;
overflow:auto;
width: 10%;
height: 400px;
border: 1px solid black;
display: inline-block;
float:left;
margin-left:20%;
}
#countryInfo {
text-align:center;
overflow:auto;
width: 49%;
height: 400px;
margin-right: 20%;
border: 1px solid black;
display: inline-block;
float:right;
}
button {
margin-left:15px;
margin-top:10px;
padding:5px;
margin-bottom:10px;
}
Javascript:
$(document).ready( function(){
var fieldInput = "";
var countrylist = "";
var countryinfo = "";
var countryjson = "getCountryListAsJSON.php";
$( "#countryInput" ).keyup(function( event ) {
fieldInput = $(this).val();
// show that something is loading
$('#actualList').html("<b>Loading response...</b>");
$.ajax({
type: 'GET',
url: countryjson,
data: fieldInput,
dataType: "json"
})
.success(function(data){
alert("success");
countrylist =data;
console.log(countrylist[1]);
$('#actualList').html(countrylist);
})
.done(function(data){
})
.fail(function() {
// just in case posting your form failed
$('#actualList').html("Failed to find countries.");
});
});
$( "#countryInput" ).focus(function() {
$("#countryInput").val("");
$("#actualInfo").html("");
$("#actualList").html("");
fieldInput="";
});
});;
the php script that was provided
<?php
// Name: getCountryListAsJSON.php
// Desc: Gets a sorted list of country names from the world DB which
// begin with the specified letters
// Params: country - beginning string of letters to match
// Outputs: JSON encoded array of country names (strings)
//get argument if provided
if(isset($_GET['country']))
$country = $_GET['country'];
else
$country = "no country specified!"; //will match nothing
//connect to database
$con = mysqli_connect("localhost", "worlddemo", "worldpass", "world")
or die("Some error occurred during connection " . mysqli_error($con));
//run query
$query = "SELECT * FROM country WHERE Name LIKE '$country%' ORDER BY name";
$results = mysqli_query($con, $query);
//build an array of strings (country names) from results
$countryList = array();
while($row = mysqli_fetch_array($results))
{
$countryList[] = htmlentities($row['Name'], ENT_COMPAT, 'UTF-8');
//note: special characters caused problems, hence htmlentities
}
//finish up
mysqli_close($con);
echo json_encode($countryList);
?>
I only get it returned as an undefined.
So I am trying to pass whatever is put in the text input to php.
For each key it is supposed to return a list of countries from a Database (hosted on my localhost xampp)
Im not sure whether its a problem with my teachers PHP or if I am just missing something in my code. I have been trying to just get it to write out in the console to see if I am getting a proper return, but the only thing that seems to be happening is it is returning undefined.
link to the world db http://downloads.mysql.com/docs/world.sql.zip
Access "getCountryListAsJSON.php" file directly from your browser (http://your-server/getCountryListAsJSON.php) and see what happens. If its all ok on the server side, you should see something like this on the page: ["country1", "country2", "country3", ... ]
Another thing you can try is change your success callback to something like this:
.success(function(data){
//alert("success");
var countrylist = data;
var html = "";
for( var i in countryList ){
html += countryList[i];
}
$('#actualList').html(html);
})

How to show loader image with message at center & prevent bootstrap modal dialog box from closing while AJAX response is coming from PHP file?

I'm using Bootstrap v 3.0.0. I've following HTML code of Bootstrap Modal:
<div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Submit Form</h4>
</div>
<div class="modal-body" style="max-height: 300px; overflow-y: auto;">
<br/>
<!-- The form is placed inside the body of modal -->
<form id="request_form" method="post" class="form-horizontal" enctype="multipart/form-data" action="">
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Reg ID <span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="reg_id" id="reg_id"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Reg Date<span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="text" class="form-control date_control" id="reg_date" name="reg_date" value="" placeholder="yyyy-mm-dd">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Upload Image<span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="file" name="reg_image" id="reg_image" accept="image/*" capture="camera" />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-5">
<button type="submit" class="btn btn-success" id="btn_receipt_submit">Submit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
For above bootstrap modal I've written following AJAX-jQuery code :
$('#request_form').submit(function(e) {
var form = $(this);
var formdata = false;
var reg_id = $('#reg_id').val();
var reg_date = $('#reg_date').val();
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'xyz.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
beforeSend: function() {
$(".btn").prop('disabled', true); // disable both the buttons on modal
},
success: function(response) {
$(".btn").prop('disabled', false); // enable both the buttons on modal
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
$('#newModal').modal('hide');
$('#Modal2').modal('show');
}
}
});
e.preventDefault();
});
I want to show some appropriate loader image exactly at the the center of the screen along with the message "Your request is processing...please wait" when the AJAX request goes to PHP file and it should be displayed exactly at the center of the screen until the response from PHP file comes.
Also during this time user should not be able to close the modal, nor it should get hidden if user clicks anywhere apart from the modal. In other words, until the response from PHP file comes user should not be able to do anything.
I tried many tricks but I'm only able to disable the two buttons appearing on form until the response comes. But actually I want to do much more than this.
Here is what you could do:
Use css to create a spinning icon
As for the positioning of the icon and message do the following:
create div that covers the whole page
set the z-index to a high value, higher than that of modal
use css to center content in the div
the div should initially be hidden
when the submit event fires the div is made visible which then disables any user action
Use the following JavaScript:
The JavaScript:
$(function() {
var mod1 = $('#newModal'),
mod2 = $('#modal2'),
btn = $('.open-form'),
ldg = $('#loading');
mod1.add(mod2).modal({show: false});
btn.on('click', function() {
mod1.modal( 'show' );
});
$('#request_form').submit(function(e) {
e.preventDefault();
ldg.find('> div > span').text('Please wait as your file is uploaded')
.end().show();
var form = $(this);
var formdata = false;
var reg_id = $('#reg_id').val();
var reg_date = $('#reg_date').val();
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : formAction,
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
ldg.hide();
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
$('#newModal').modal('hide');
$('#Modal2').modal('show');
}
}
});
});
});
The Demo:
DEMO
http://jsfiddle.net/cnvusn04/2/
CSS:
.modal {
text-align: center;
}
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
JQ:
$('#myModal').modal({
show:false,
})
// prevents closure while the ajax call is in progress
$('#myModal').on('hide.bs.modal', function (e) {
if(inProgess == true)
return false;
})
var inProgess = false;
ajaxCall();
function ajaxCall()
{
inProgess = true;
$('#myModal').modal('show');
//simulates the ajax call
setTimeout(function(){
inProgess = false;
$('#myModal').modal('hide');
}, 5000);
}
Notice that i expect that your question should be close cause it is "too broad".
You can try to disable the mouse event on the modal:
$(".modal").css('pointer-events','none');
See also: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
The above does not disable the button (used to open the modal), but you can keep your first solution. Also notice that you will have to set the modal's keyboard option false to pevent closing with the escape key.
Alternatively you code set a overlay with a higher z-index than the modal
CSS:
html, body{
height:100%;
}
#disableall{
position: absolute;
width: 100%;
height:100%;
z-index:1050;
background-color: rgba(255,0,0,0.5);
display:none;
}
html directly after the <body> tag:
<div id="disableall"></div>
javascript:
beforeSend: function() {
$("disableall").show();
},
it worked for me try like this
css
#pageloaddiv {
position: fixed;
margin: 0px;
width: 100%;
height: 100%;
z-index: 100000;
background: url('../img/ajax-loader.gif') no-repeat center center rgba(0, 0, 0, 0.38);
}
html
<div id="pageloaddiv" style="display: none;"></div>
javascript
$.ajax({
url: 'your url',
beforeSend:function(){
$('#pageloaddiv').show();
},
success: function() {
$('#pageloaddiv').hide();
$('#newModal').hide();
},
});
is there anything wrong with using something like font awesome icons that are animated
<i class="fa fa-spin fa-3x"></i>
the above then might do the trick for you

Categories

Resources