Ajax and output pdf file are not working together - ajax

I have a file named download.php and call getpdf function inside it.
I call download.php via ajax to download pdf file when users click download button. but nothing happend and no download window appears. I checked it in firebug Net tab and download.php are requested on click event. Its size also changes that shows the file is reading from its location,but no download window.
Here's getpdf code:
function getpdf($id) {
header('Content-Type: application/pdf');
readfile('/san/theo-books/PDFs/'.$id.'.pdf');
exit;
}
And here's download.php code:
$pdf_id = $_POST('pdi');
echo getpdf($pdf_id);
What is the problem? Would you help me?

Here is the full postback version. It's not using the jQuery Ajax, because Popup download window needs the full postback:
<a id="pdf-10" href="#">PDF Export</a>
$(document).ready(function () {
$('a[id^="pdf"]').click(function (event) {
event.preventDefault();
var pdfExportPath = "/san/theo-books/PDFs/";
var $a = $(this);
var postId = $a.attr('id').replace("pdf-","");
var form = $('<form action="' + pdfExportPath + '" name="pdf' + postId + '" id="pdf' + postId + '" method="POST"> <input id="id" name="id" type="hidden" value="' + postId + '" /></form>');
$(form).appendTo('body');
form.submit();
});
});

Related

Google script automatically close UI after clicking link button

I have a script that opens a UI which is used to open another spreadsheet
When I click to open the link I would like the UI to close automatically if possible.
function ServiceSetServiceSheets(){
var html = "<a href='https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxx'; target='_blank'>Open The Service Sheet</a>";
var anchor = HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME).setHeight(60).setWidth(150);
SpreadsheetApp.getUi().showModalDialog(anchor,"Click the link to")
}
Can anyone help please?
In your situation, how about using google.script.host.close() as follows? Please modify your script as follows.
From:
var html = "<a href='https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxx'; target='_blank'>サービス シートを開く";
To:
var html = "<a href='https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxx'; target='_blank' onclick='google.script.host.close()'>サービス シートを開く";
By this modification, when you click the link, the dialog is closed by google.script.host.close().
Example:
Execute launchClickAndClose();
function launchClickAndClose() {
let html = '<!DOCTYPE html><html><head><base target="_top"></head><body>';
html += '<input type="button" value="Doit" onClick="doSomething();" />';
html += '<script>function doSomething(){google.script.run.withSuccessHandler(() => {google.script.host.close()}).doitontheserver();}</script>'
html += '</body></html>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Close Automatically")
}
function doitontheserver() {
const ss = SpreadsheetApp.getActive();
ss.toast("Doing it");
return;
}

Loading data from a kendo grid into a kendo window

grid with a custom command to open a kendo-window with detailed data. Like described here:
http://demos.telerik.com/kendo-ui/grid/custom-command
I load the data for the grid as json via php script f.e. employees.php.
In the example by clicking on the "View Details" the windows loads Data from the same datasource.
What i need is to load detail data from another php/json file. I found out that it should work with the "refresh" Method, but i didn't get it to work.
Can anybody help me out?
UPDATE
Thanks to #Karthikeyan my code now looks like this:
<script>
... function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var dataItemID = dataItem.AK_ID;
$.getJSON('data/akDetail.php?ak=' + dataItemID + '', function (data) {
wnd.content(detailsTemplate(data));
wnd.center().open();
});
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= title_dataitem #</h2>
</div>
</script>
the kendo window does not open, i get an error in the chrome console: "Uncaught ReferenceError: title_dataitem is not defined"
In the demo grid, the line wnd.content(detailsTemplate(dataItem)); binds the template with data of the current row. You can instead do something like
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.getJSON('/dataSource.php', { param1: dataItem.param1, param2: dataItem.param2 }, function (data) {
wnd.content(renderTemplate(data));
wnd.center().open();
});
}
The renderTemplate method can generate HTML markup using the data received from server and will get dumped as content inside the window.
Update: renderTemplate method can either be a kendo template that expects the data from the akDetail.php call or a custom implementation that returns HTML markup which can be used as modal window's content. For example,
function renderTemplate(dataItem) {
var markup = $('<div id="details-container"> ' +
'<h2 class="firstName"></h2> ' +
'<em class="title"></em> ' +
'<dl> ' +
'<dt class="city"></dt> ' +
'<dt class="dob"></dt> ' +
'</dl> ' +
'</div>');
markup.find('h2.firstName').html(dataItem.firstName);
markup.find('em.title').html(dataItem.title);
markup.find('dt.city').html(dataItem.city);
markup.find('dt.dob').html(kendo.toString(dataItem.dob, "MM/dd/yyyy"));
}

jQuery cleditor plugin: creating a new button

Using cleditor, I'm trying to set up a custom button with the following code:
(function($) {
$.cleditor.buttons.link_species = {
name: "link_species",
image: "fish.gif",
title: "Species Link",
command: "inserthtml",
popupName: "link_species",
popupClass: "cleditorPrompt",
popupContent: "Genus: <input type='text' size='15'> Species: <input type='text' size='15'><br />Remove italics? <input type='checkbox' value='remove'> <input type='button' value='Ok' />",
buttonClick: link_speciesClick
};
// Handle the hello button click event
function link_speciesClick(e, data) {
// Wire up the submit button click event
$(data.popup).children(":button")
.unbind("click")
.bind("click", function(e) {
// Get the editor
var editor = data.editor;
var $text = $(data.popup).find(":text"),
genus = $text[0].value,
species = $text[1].value;
var slug = genus + '-' + species;
slug = htmlEntities(slug);
var link = '/dev/species/' + slug + '/';
var rel = link + '?preview=true';
var display = firstUpper(genus) + ' ' + species;
// Get the entered name
var html = '' + display + '';
if ( !$(data.popup).find(":checkbox").is(':checked') ) {
html = '<em>' + html + '</em>';
}
// Insert some html into the document
editor.execCommand(data.command, html, null, data.button);
// Hide the popup and set focus back to the editor
editor.hidePopups();
editor.focus();
});
}
})(jQuery);
It's a WordPress website, and the directory structure is something like this:
/wp-content/plugins/sf-species-profile/cleditor
Within there I have all the cleditor files and config.js.This file is where the above code is stored.
I also have an images folder containing a 24*24 fish.gif file.
For some reason, when I run this code, I get the following error:
[firefox]
a is undefined
<<myurl>>/wp-content/plugins/sf-species-profiles/cleditor/jquery.cleditor.min.js?ver=3.3.1
Line 17
[chrome]
Uncaught TypeError: Cannot read property 'length' of undefined
If I change the "image" argument to image:"" the same image for "B" appears, but the plugin works without error.
Does anyone have any ideas what may be wrong?
It would be easier to debug with the non minimized version. You can get it from here: http://premiumsoftware.net/cleditor/ (zip)
There are 2 functions that include a length call in the code that ends up in line 17 of the minimized code. One in the function hex(s) that processes color. The other is the the imagePath function.
function imagesPath() {
var cssFile = "jquery.cleditor.css",
href = $("link[href$='" + cssFile +"']").attr("href");
return href.substr(0, href.length - cssFile.length) + "images/";
}
It could throw an error of the type you have if your rendered html doesn't include a line like "<link rel="stylesheet" type="text/css" href="path/to/jquery.cleditor.css" />". (Href would then be undefined.)
For wordpress integration, you may find it easier to setup when using the wordpress plugin version of cleditor.

How can I return an id value from a div already populated through ajax

I am having some difficulty passing a correct id function back to AJAX.
I'm creating a product bulletin generator that lets items to be added by their SKU code (which works fine). My problem is that when a bulletin is clicked on, a preview of that bulletin is loaded into a div and shows all products associated with that bulletin.
From inside those results, I am trying to add the ability to delete a product from the bulletin. The problem is that the value being passed back to AJAX belongs to the first product only. It won't send the value belonging to the particular item if it is any other item than the first one.
This is the code (belonging to main.php) that gets loaded via AJAX into a div and is looped with each product associated with a selected bulletin
echo "<form name='myDelForm'>
$news_gen_id<br>
<input type='hidden' id='delccode' value='".$news_gen_id."'>
<input type='hidden' id='deledit' value='".$edit."'>
<input type='button' onclick='ajaxDelCcode()' value='Delete' /><br></form>
</td>";
The AJAX code (on index.php, where the div that calls in main.php is also located) is this
function ajaxDelCcode(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new
ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxMain2");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var deledit = document.getElementById("deledit").value;
var delccode = document.getElementById("delccode").value;
var queryString = "?delccode=" + delccode + "&deledit=" + deledit;
ajaxRequest.open("GET", "main.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
Currently, using those two pieces of code, I can successfully delete only the first product. The delccode variables do not seem to change when the products are looped (although when I echo the variables during the loop, it is definitely changing to the appropriate value...it's just not passing it correctly back to AJAX.)
I tried taking the AJAX code, putting it inside the main.php product loop, and change the function name during each loop (so ajaxDelCcode$news_gen_id() for example) and also to the button itself so that it is calling the AJAX specific to it. And it works if you are visiting main.php directly...but not from index.php after main.php has been called into the div.
I can't figure out how to pass the correct looped value from main.php within the div, back to the AJAX code on index.php
Can anyone help me with this?
Thanks,
Dustin
Instead of storing the id in the input, just pass it as an argument to the function:
function ajaxDelCcode(delccode) { ...
<input type='button' onclick='ajaxDelCcode(\"".$news_gen_id."\")' value='Delete' />
Also, I'd swap the quotes if I were you. Or better yet, instead of using echo, break the PHP code and just write HTML:
<? ... ?><input type="button" onclick="ajaxDelCcode('<?= $news_gen_id ?>')" value="Delete" /><? ... ?>
What does the code you use to delete look like? Is it in the same php file as the form you posted above? If so, is the form getting submitted to itself accidentally? Like perhaps when a user presses enter while on an input type=text control? I understand that you want to do this by ajax but I am suspecting that the form is your problem.
Seconding the jQuery comment.
Here try this
1) add jquery to your document.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
2) give your inputs name attributes
<input type='hidden' name='delcode' id='delccode' value='".$news_gen_id."'>
<input type='hidden' name='deledit' id='deledit' value='".$edit."'>
3) Use a function something like this instead of all that code above
function ajaxDelCcode() {
$.ajax({
url: "main.php",
type: "GET",
dataType: "text",
data: $("#myDelForm").serialize(),
success: function(rText) {
$("#ajaxMain2").text(rText);
}
});
}

edit-in-place, how to make more db fields editable

Good evening guys!
I just managed to implant a really sweet working edit-in-place function with jQuery and AJAX. I'm able to edit 1 db field. I would like to be able to edit multiple db fields.
These are all the scripts:
Update query (handler.php)
<?php
include('../../core/additional/connect-db.php');
if (isset($_POST['id']) && isset($_POST['firstname'])) {
$firstname = mysql_real_escape_string($_POST['firstname']);
$id = mysql_real_escape_string($_POST['id']);
$query = "UPDATE players SET firstname ='$firstname' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
?>
And the ajax in the head
<script type="text/javascript">
$(document).ready(function()
{
$(".editable").hover(
function()
{
$(this).addClass("editHover");
},
function()
{
$(this).removeClass("editHover");
}
);
$(".editable").bind("dblclick", replaceHTML);
$(".btnSave, .btnDiscard").live("click", handler);
UI("Ready");
function UI(state)
{
var status = {};
status.Ready = "Ready";
status.Post = "Saving your data. Please wait...";
status.Success = "Success! Your edits have been saved.";
status.Failure = "Attempts to save data failed. Please retry.";
var background = {};
background.Ready = "#E8F3FF";
background.Post = "#FAD054";
background.Success = "#B6FF6C";
background.Failure = "#FF5353";
$("#status").animate({opacity: 0}, 200, function (){$("#status").html(status[state]).css({background: background[state]}).animate({opacity: 1}, 200)});
}
function handler()
{
var selector="";
var code="21";
if ($(this).hasClass("btnSave"))
{
UI("Post");
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
timeout: 100,
url: "core/actions/handler.php",
data: str,
success: function(msg){code = msg; $(".message_edit").show(); $(".message_edit").fadeOut(2500);},
});
if(code == 1)
{
UI("Success");
selector = "editBox";
}
else
{
UI("Failure");
selector = "buffer";
}
}
else {selector = "buffer"}
$(this).parent()
.html($(this).siblings("form")
.children("."+selector)
.val())
.removeClass("noPad editHover")
.bind("dblclick", replaceHTML);
return false;
}
function replaceHTML()
{
var buffer = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("")
.html("<form class=\"editor\"><input type=\"text\" name=\"firstname\" class=\"editBox\" value=\"" + buffer + "\" /> <input type=\"hidden\" name=\"buffer\" class=\"buffer\" value=\"" + buffer + "\" /><input type=\"hidden\" name=\"id\" class=\"record\" value=\"" + $(this).attr("id") + "\" /></form>Save Cancel")
.unbind('dblclick', replaceHTML);
}
}
);
</script>
Then the field is displayed and editable by using this:
<td class="editable" id="' .($id). '" width="180">' .($task). ' </td>
I might be able to copy and rename all scripts, but I'm positive that's not the ideal way to do it. I tried to copy the script in the handler.php file and renamed the db fields, and did the same for the ajax script. But it didn't work. I hope my 'problem' is clear to you, any suggestions?
Note: I think the solution lies somewhere in this line (bottom of the ajax script):
.html("<form class=\"editor\"><input type=\"text\" name=\"firstname\" class=\"editBox\" value=\"" + buffer + "\" /> <input type=\"hidden\" name=\"buffer\" class=\"buffer\" value=\"" + buffer + "\" /><input type=\"hidden\" name=\"id\" class=\"record\" value=\"" + $(this).attr("id") + "\" /></form>Save Cancel")
Thanks in advance for helping out! :)
You may want to look at using the Jeditable jQuery plugin (http://www.appelsiini.net/projects/jeditable) and for a good example of various uses you can look at the demo page:
http://www.appelsiini.net/projects/jeditable/default.html
Also, I hope you are not actually going to use that php script to update the database, as that is vulnerable to SQL injection attacks, so it is bad practice.
And I don't see any element with the class editable in the html, just editBox.
And finally, you are submitting all the elements each time there is to be a change? That is quite inefficient, as one advantage of editing in-place is to just send small changes each time.

Resources