Ajax call closes popup window when generating pdf using mPDF in PhP - javascript

I am tring to create PDF using mPDF library. I have data in popup window and I am passing whole HTML of the popup onto PDF. But when I click on the button popup closes.
<a data-html="true" data-container="body" class="tips ajax-popup-link '.$prev_status.'" href="popup-details.php" title="'.$details.'" data-params="id='.$bookings[$room_id][$prev_date][$n]['bookid'].'"></a>
pop-details.php , part where I have JS function :
function printElem1(elem){
var ele = $("#"+elem);
ele.find("a").remove();
ele.find("button").remove();
var popup = '<html><head><title>'+document.title+'</title><link rel="stylesheet" media="print" href="<?php echo DOCBASE.ADMIN_FOLDER.'/css/print.css'; ?>"/><style media="print">th, td, {padding: 8px !important;line-height: 1.42857143;vertical-align: top;} th{text-align:center;} strong { font-weight: bold; }</style></head><body>'+ele.html()+'</body></html>';
popup = popup.replace(/(\r\n|\n|\r|\t| )/gm, "");
popup = JSON.stringify(popup);
//alert(popup);
var name = ele.find("h2").text();
name = name.replace(" ", "_");
//console.log(popup);
ele.click();
setTimeout(function(){
$.ajax({
// alert(popup);
type: 'POST',
url: 'pdf_download.php',
data: {name: name,popup: popup},
success: function(data){
}
});
}, 600);
return true;
}
pdf_download.php :
if(isset($_SESSION['user']['id'])){
$variable = json_decode($_POST['popup']);
alert($variable);
// die();
$mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'format' => [240, 200]]);
$mpdf->SetTitle($_POST['name']);
$mpdf->WriteHTML($variable);
$mpdf->Output($_POST['name'].'.pdf', 'I');
}
Calling in pop-details.php :
<i class="fas fa-file-pdf"></i>
I have checked popup content using alert(popup); and it show all the data. Please advice. Thanks.

Related

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

How to fix a problem with drag and drop JS?

With this code I want to drag and drop image.
When I drop, for each element I call with ajax a php page to creare a record in db.
Ajax return to me a data.object to put the element in my html page.
I have this JS code to control a drag and drop files from computer...
var listaId = new Array();
function dropHandler(ev) {
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
var div = document.getElementById('raccoltaFile');
var percorso = div.getAttribute('data-percorso');
var id = div.getAttribute('data-id');
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
var foto = new FormData();
foto.append('fotoOggetto', file);
foto.append('nome', file.name);
foto.append('percorso', percorso);
foto.append('idSottocat', id);
$.ajax({
url: '../php/model.php?az=dragDropImage&id='+id+"&percorso="+percorso,
data:foto,
processData:false,
contentType:false,
type: 'POST',
dataType: 'json'
})
.done(function(data){
if(data.doc_id) {
$("#raccoltaFile").append("<div class='row' style='border-bottom: solid 2px grey'><div class='col-3'><img class='img-thumbnail' src='"+data.doc_url+"' /></div><div class=col-4>"+data.doc_nome_file+"</div><div class='col-3'><button class='btn btn-danger' onClick='cancellaFotoProvvisoria()'>Elimina</button></div></div>");
listaId.push(data.doc_id);
} else {
alert("Hai inserito un'immagine fuori dai parametri accettati");
}
})
.fail(function(){
alert("Qualcosa รจ andato storto.");
});
}
}
}
alert(listaId);
}
The first element id I drag and drop does not enter to listaId array but the second one yes.
You say why?

Unable to pass small image to modal popup and display it

I am creating image elements of load of a page and written the code in AJAX POST jquery method for it. So small icons of image are coming on page. When I click on the image on document.ready(onclick) it must open big in modal pop up but it is not opening.However blank pop up is opening.
loadup.js code
$.ajax({
type: "POST",
url: "php/loadimages_f.php",
dataType : 'json',
success: function (result) {
//alert(result);
if(result==0){
$("#friends_list_insert").after(" No Friends Yet...");
}
else{
for(var i = 0; i < result.length; i++)
{
var PP_PATH;
PP_PATH="php/"+result[i].Photo_URL;
var li_post="<li class='imggalli' style='list-style:none;'><a
href='#' data-toggle='modal' data-target='#myModal2' class='thumbnailimg' title='Image"+i+"'><img src='"+PP_PATH+"' style='margin:2px;width:65px;height:65px;' class='img-responsive' id='img"+i+"'></a></li>";
$("#img_gallery_append").append(li_post);
}
}
}
});
now on page code
// Function for image pop up
$(document).ready(function() {
$('img').on('click', function() {
$("#showImg").empty();
// alert(this.id);
var image = $(this).attr("src");
$("#showImg").append("<img class='img-responsive' src='" + image + "' />")
})
});
What is the problem ? Could anyone help please ? ( Objective is opening the small image on the modal pop up..)
try to correct this
PP_PATH="php/"+result[i].Photo_URL;
with
PP_PATH="php/"+result.d[i].Photo_URL;
because result is object, and you need to catch the data with d

Json table update after certain date

At the moment i have this code
// JavaScript Document
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://api.import.io/store/data/93296dfc-1edb-4aa6-a3e5-2207fa52f3ea/_query?input/webpage/url=http%3A%2F%2Fwww.seatwave.com%2Fthe-script-tickets%2Fseason&_user=687c839c-f236-4817-90c9-f6eb81334c2a&_apikey=pvXHYMTbZD3Za3TB%2Bn8LgVybPltV1a379yBNfSfzepw2piIhs%2FxHinVseH7G4BwItVQ57aNJnyk6g6g%2BAxyEMg%3D%3D',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].name;
var venue = json.results[i].venue;
var date = json.results[i].date;
var button = "<button class='btn btn-info' data-url='"+(i+1)+".html'>Compare</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".btn.btn-info").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error: function(error){
console.log(error);
}
});
This appends the URL to a table. However as you can see this code here data-url='"+(i+1)+".html' created the button with an increment of 1 on the amount of buttons listed.
The issue is, this api is updating every 5 hours. When the event passes, The buttons need to really be updated. Otherwise the whole site breaks.
So the question is how could i go around making the links unique and update when an event passes? whilst im writing this i believe i could just use the Date function, So the code would be
data-url='"+date+".html'
Any other suggestions would be great?
There are many ways you could do this. The easiest would be to add a meta tag to the page that forces it to refresh each 5 hours. If for some reason you need to do it with code, then you'll need to add a timer that checks for updates and refreshes the button data. A working example of that is shown below. The data does have a time stamp, but it's set to the far future. So rather than check that the code simply updates each 10 seconds (you can set to whatever frequency you need).
<html>
<body>
<style type="text/css">
table { border-collapse: collapse; font-family: sans-serif; font-size: 12px;}
table td { border: 1px gray dotted; padding: 2px;background-color:aliceblue;}
table caption {font-weight: bold; color: firebrick;}
</style>
<table id="apple"><caption></caption><tbody></tbody></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var lastUpdate;
function update() {
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://api.import.io/store/data/93296dfc-1edb-4aa6-a3e5-2207fa52f3ea/_query?input/webpage/url=http%3A%2F%2Fwww.seatwave.com%2Fthe-script-tickets%2Fseason&_user=687c839c-f236-4817-90c9-f6eb81334c2a&_apikey=pvXHYMTbZD3Za3TB%2Bn8LgVybPltV1a379yBNfSfzepw2piIhs%2FxHinVseH7G4BwItVQ57aNJnyk6g6g%2BAxyEMg%3D%3D',
success: function (json) {
/*
Removed - data time stamp does not appear to be useful
if (json.results[0].date == lastUpdate) return;
lastUpdate = json.results[0].date;
$("#apple caption").html( 'Last Updated: ' + lastUpdate );
*/
$("#apple caption").html( "Last Updated: " + (new Date()).toString() );
$("#apple tbody").html( "" );
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].name;
var venue = json.results[i].venue;
var date = json.results[i].date;
var button = "<button class='btn btn-info' data-url='"+(i+1)+".html'>Compare</button>";
$("#apple tbody").append("<tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr>");
$("#apple").find(".btn.btn-info").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error: function(error){
console.log(error);
}
});
}
update();
var timerId = setInterval( update, 10000 );
</script>
</body>
</html>

Creating textarea and buttons dynamically

I am facing issues with creating a dynamic textarea and 'Add' and 'Edit' buttons for every new paragraph.
DEMO of what I have managed so far:
The 'Add' button is for creating new paragraphs. The user should see a textarea where they enter the content for new paragraph. The first time they click 'Add' button, the text on the button will change to 'Save', the second time they click 'Save' it should append the paragraph to the div and assign it a unique id, which will be used to reference it with the new 'Add' and 'Edit' buttons.
The 'Edit' button is for editing the paragraph from which the 'Edit' button was clicked. To make the paragraph editable I'm using jquery editable (jeditable). Below are appropriate links to jeditable plugin:
plugin documentation
jeditable live demo
All the paragraph load from the back-end. Using PHP to load paragraphs:
<div class="paragraphs">
<?php
foreach($notes['children'] as $overview) :
if ($overview['type'] == 'Paragraph') :
?>
<div id="block1">
<p class='edit1'><?php echo $overview['content']; ?></p>
<p>
<?php if (isset($subject) && $subject==true) : ?>
<div id="para1">
<p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
<button id="add1" class="add1 success tiny">Add</button>
<button id="startEdit1" class="canEdit1 tiny">Edit</button>
</div>
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
The 'Add' and 'Edit' button functionality:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
var $subject_id = "<?php echo $subject_id ?>";
var $teacher_id = "<?php echo $teacher_id ?>";
// Define our elements
var $lock = false;
//Make the elements editable
function makeThingsEditable() {
$editables.editable({
emptyMessage : '<em>Please write something...</em>',
callback : function( data ) {
$info.hide();
$info.eq(0).show();
}
});
}
function ajaxRequest(data, method_url, request_type) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP/1.1', '200');
}
});
var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
var params = 'inputJson=' + data;
var post = $.ajax({
type: request_type,
url: eurl,
data: params,
success: function(result) {
console.log('result: '+result);
console.log('data: '+params);
},
async: false
});
//alert(post.responseText);
return post.responseText;
console.log(post.responseText);
}
// Edit paragraph button
// Button that toggles the editable feature
var i = 1;
var $editables = $('.edit'+i);
$('.canEdit'+i).click(function() {
if( $editables.is(':editable') ) {
//need to call save action here and pass in updated JSON
if ($(this).text() == 'Save changes')
{
var text = $(".edit"+i).text();
// ajax request
var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
ajaxRequest(datum, 'editNotes', 'POST'); // POST request on editNotes
ajaxRequest(datum, 'loadNotes', 'GET'); // GET request on loadNotes
// jquery request
$.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
//console.log(data);
alert( data );
});
}
$editables.editable('destroy');
this.innerHTML = 'Edit';
i++;
} else {
makeThingsEditable();
this.innerHTML = 'Save changes';
// TODO h4kl0rd: make $editables selectable
}
});
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
$('#add'+i).click(function(){
if ( $(this).text() == "Add" ) {
$('#textarea'+i).show();
$(this).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $(this).text() == "Save" ) {
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$(this).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
Any help is appreciated.
change these:
$('.canEdit'+i).click(function() {
$('#add'+i).click(function(){
to these:
$(document).on('click', '.canEdit'+i, function() {
$(document).on('click', '#add'+i, function() {
What seemed to me is your buttons are dynamic and they can't take direct event binding. So instead you have to delegate the event to the closest static parent which is $('.paragraphs') or to $(document) itself because it is always available.
So if you are using closest static parent then you have to put your event handlers inside doc ready and if you are using $(document) then its not needed.
$(function(){
var i = 1;
var $editables = $('.edit'+i);
$('.paragraphs').on('click', '.canEdit'+i, function() {
// all your edit stuff
});
$('.paragraphs').on('click', '#add'+i, function() {
// all your addstuff
});
});

Categories

Resources