How to add upload utility to wmd editor? - upload

Has anyone succeeded to do this?

I accomplished this by replacing Util.prompt with my own jquery.dialog method. The prompt function takes a parameter as a callback, making it easy to create a drop-in replacement.
if (isImage) {
// OLD: util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
// WMD_IMAGE_GALLERY_URL loaded from a global settings elsewhere
util.imageGallery(WMD_IMAGE_GALLERY_URL, makeLinkMarkdown);
}
else {
util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
}
If you're interested, I wrote a blog entry about it (with pictures!) which has some more sample code as well as some of the problems/solutions I encountered in implementing this.

The following hack requires use of jQuery, jQuery UI and Mike Alsup's jQuery Form Plugin for performing AJAX file uploads. The hack works with the linked versions (jQ 1.7.2 and jQUI 1.8.20). I can't guarantee compatibility with other versions.
In your <head>, you'll need to include the dependencies:
<script type='text/javascript' src='jquery.min.js'></script>
<link href='theme/jquery-ui.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' src='jquery-ui.js'></script>
<script type='text/javascript' src='wmd/showdown.js'></script>
<script type='text/javascript' src='wmd/wmd.js'></script>
<link type='text/css' rel='stylesheet' href='wmd/wmd.css'/>
<script type='text/javascript' src='jquery.form.js'></script>
We actually need to make a single change to wmd.js.
Go on in there and search (ctrl+f) for var form = doc.createElement("form");
Immediately following this line, assign the form an id, dialogform will do: form.id = "dialogform";
Now on the front end, run:
$(document).ready(function(){
$("#wmd-image-button").live("click",function(){
setTimeout(function(){
$(".wmd-prompt-dialog").css({"opacity": "0", display: "none"});
}, 100);
var $div = $("<div>");
var $form = $("<form>").attr({action: "submit_image.php", method: "post"})
var $file = $("<input/>").attr({type: "file", name: "image"});
var $name = $("<input/>").attr({type: "text", name: "name", placeholder: "Name"});
var $submit = $("<input/>").attr("type", "submit");
$form.append($name, $file, $submit).ajaxForm(function(r) {
r = $.parseJSON(r);
if(r.success){
$("#dialogform input[type='text']").val(r.filename);
$("#dialogform input[value='OK']").trigger("click");
$div.dialog("close");
}
});
$div.append($form).dialog({title: "Upload Image"});
});
$("#wmd-link-button").live("click", function(){
setTimeout(function(){
$(".wmd-prompt-dialog").css("opacity", "1");
}, 100);
});
});
Remember, the post was written for jQuery 1.7.2, and live() has since been deprecated. Please switch to on() if you're using a more recent version of jQuery
And on the backend, in submit_image.php:
$f = $_FILES['image'];
$p = $_POST;
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($f['tmp_name']);
if(in_array($detectedType, $allowedTypes)){
$pi = pathinfo($f['name']);
$ext = $pi['extension'];
$target = "img/" . strtolower(str_replace(" ", "-", $p['name'])) . "." . $ext;
if(move_uploaded_file($f['tmp_name'], $target)){
$returnArr = array(
"success" => true,
"filename" => site_url($target)
);
echo json_encode($returnArr);
}
else echo json_encode(array("success" => false));
}
else echo json_encode(array("success" => false, "msg" => "Invalid File Type."));
Hopefully that will get you started. This was written a couple of years ago, when my javascript skills were sub-par! Haha. I previously had this on a blog (which is now dead), with step-by-step instructions and explanations; lots of unnecessary fluff. Thanks #Kamiccolo for bringing this link to my attention. I had to consult the way-back-machine in order to revive it.

Add a button to the control panel of WMD.
Search for the following string to find the place where buttons are being added:
italicButton.XShift
In my version, the function is in class SpritedButtonRow and is called build.
Ignore the setup and textOp attributes. XShift is the position of the button image in the css sprite that comes with WMD, Instead of that, give the button a class and in the class specify the background image. Then Just add an onclick event to the button
that will do what you need it to do.
But, I don't think an upload button should be inside a text editor, does not make sense.

Related

hide browser back button after user gets logout [duplicate]

I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.
I have tried the following script, but it stops my timer.
What should I do?
The timer is stored in file cdtimer.js.
<script type="text/javascript">
window.history.forward();
function noBack()
{
window.history.forward();
}
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">
I have the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?
There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:
window.onbeforeunload = function() { return "Your work will be lost."; };
This page does list a number of ways you could try to disable the back button, but none are guaranteed:
http://www.irt.org/script/311.htm
It is generally a bad idea overriding the default behavior of the web browser. A client-side script does not have the sufficient privilege to do this for security reasons.
There are a few similar questions asked as well,
How can I prevent the backspace key from navigating back?
How can I prevent the browser's default history back action for the backspace button with JavaScript?
You can-not actually disable the browser back button. However, you can do magic using your logic to prevent the user from navigating back which will create an impression like it is disabled. Here is how - check out the following snippet.
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var noBackPlease = function () {
global.location.href += "#";
// Making sure we have the fruit available for juice (^__^)
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
noBackPlease();
// Disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// Stopping the event bubbling up the DOM tree...
e.stopPropagation();
};
}
})(window);
This is in pure JavaScript, so it would work in most of the browsers. It would also disable the backspace key, but that key will work normally inside input fields and textarea.
Recommended Setup:
Place this snippet in a separate script and include it on a page where you want this behavior. In the current setup it will execute the onload event of the DOM which is the ideal entry point for this code.
Working DEMO!
It was tested and verified in the following browsers,
Chrome.
Firefox.
Internet Explorer (8-11) and Edge.
Safari.
I came across this, needing a solution which worked correctly and "nicely" on a variety of browsers, including Mobile Safari (iOS 9 at time of posting). None of the solutions were quite right. I offer the following (tested on Internet Explorer 11, Firefox, Chrome, and Safari):
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
history.pushState(null, document.title, location.href);
});
Note the following:
history.forward() (my old solution) does not work on Mobile Safari --- it seems to do nothing (i.e., the user can still go back). history.pushState() does work on all of them.
the third argument to history.pushState() is a url. Solutions which pass a string like 'no-back-button' or 'pagename' seem to work OK, until you then try a Refresh/Reload on the page, at which point a "Page not found" error is generated when the browser tries to locate a page with that as its URL. (The browser is also likely to include that string in the address bar when on the page, which is ugly.) location.href should be used for the URL.
the second argument to history.pushState() is a title. Looking around the web most places say it is "not used", and all the solutions here pass null for that. However, in Mobile Safari at least, that puts the page's URL into the history dropdown the user can access. But when it adds an entry for a page visit normally, it puts in its title, which is preferable. So passing document.title for that results in the same behaviour.
<script>
window.location.hash = "no-back-button";
// Again because Google Chrome doesn't insert
// the first hash into the history
window.location.hash = "Again-No-back-button";
window.onhashchange = function(){
window.location.hash = "no-back-button";
}
</script>
For restricting the browser back event:
window.history.pushState(null, "", window.location.href);
window.onpopstate = function () {
window.history.pushState(null, "", window.location.href);
};
This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.
If you combine this behaviour with an event listener on the popstate event, you can essentially set up an infinite loop of sub-states. So, you load the page, push a sub-state, then hit the back button, which pops a sub-state and also pushes another one, so if you push the back button again it will never run out of sub-states to push. If you feel that it's necessary to disable the back button, this will get you there.
history.pushState(null, null, 'no-back-button');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'no-back-button');
});
How to block coming backwards functionality:
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
None of the most-upvoted answers worked for me in Chrome 79. It looks like Chrome changed its behavior with respect to the Back button after version 75. See here:
https://support.google.com/chrome/thread/8721521?hl=en
However, in that Google thread, the answer provided by Azrulmukmin Azmi at the very end did work. This is his solution.
<script>
history.pushState(null, document.title, location.href);
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
</script>
The problem with Chrome is that it doesn't trigger onpopstate event
unless you make browser action ( i.e. call history.back). That's why
I've added those to script.
I don't entirely understand what he wrote, but apparently an additional history.back() / history.forward() is now required for blocking Back in Chrome 75+.
React
For modal component in React project, the open or close of the modal, controlling browser back is a necessary action.
The stopBrowserBack: the stop of the browser back button functionality, also get a callback function. This callback function is what you want to do:
const stopBrowserBack = callback => {
window.history.pushState(null, "", window.location.href);
window.onpopstate = () => {
window.history.pushState(null, "", window.location.href);
callback();
};
};
The startBrowserBack: the revival of the browser back button functionality:
const startBrowserBack = () => {
window.onpopstate = undefined;
window.history.back();
};
The usage in your project:
handleOpenModal = () =>
this.setState(
{ modalOpen: true },
() => stopBrowserBack(this.handleCloseModal)
);
handleCloseModal = () =>
this.setState(
{ modalOpen: false },
startBrowserBack
);
This is the way I could it accomplish it.
Weirdly, changing window.location didn't work out fine in Google Chrome and Safari.
It happens that location.hash doesn't create an entry in the history for Chrome and Safari. So you will have to use the pushstate.
This is working for me in all browsers.
history.pushState({ page: 1 }, "title 1", "#nbb");
window.onhashchange = function (event) {
window.location.hash = "nbb";
};
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
This JavaScript code does not allow any user to go back (works in Chrome, Firefox, Internet Explorer, and Edge).
This article on jordanhollinger.com is the best option I feel. Similar to Razor's answer but a bit clearer. Code below; full credits to Jordan Hollinger:
Page before:
<a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>
Page of no return's JavaScript:
// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'
// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
// Push "#no-back" onto the history, making it the most recent "page"
if ( history_api ) history.pushState(null, '', '#stay')
else location.hash = '#stay'
// When the back button is pressed, it will harmlessly change the url
// hash from "#stay" to "#no-back", which triggers this function
window.onhashchange = function() {
// User tried to go back; warn user, rinse and repeat
if ( location.hash == '#no-back' ) {
alert("You shall not pass!")
if ( history_api ) history.pushState(null, '', '#stay')
else location.hash = '#stay'
}
}
}
<html>
<head>
<title>Disable Back Button in Browser - Online Demo</title>
<style type="text/css">
body, input {
font-family: Calibri, Arial;
}
</style>
<script type="text/javascript">
window.history.forward();
function noBack() {
window.history.forward();
}
</script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
<H2>Demo</H2>
<p>This page contains the code to avoid Back button.</p>
<p>Click here to Goto NoBack Page</p>
</body>
</html>
This code was tested with the latest Chrome and Firefox browsers.
<script type="text/javascript">
history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () { history.go(1); };
</script>
Try it with ease:
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
You can just put a small script and then check. It won't allow you to visit previous page.
This is done in JavaScript.
<script type="text/javascript">
function preventbackbutton() { window.history.forward(); }
setTimeout("preventbackbutton()", 0);
window.onunload = function () { null };
</script>
The window.onunload function fires when you try to visit back or previous page through browser.
Very simple and clean function to break the back arrow without interfering with the page afterward.
Benefits:
Loads instantaneously and restores original hash, so the user isn't distracted by URL visibly changing.
The user can still exit by pressing back 10 times (that's a good thing), but not accidentally
No user interference like other solutions using onbeforeunload
It only runs once and doesn't interfere with further hash manipulations in case you use that to track state
Restores original hash, so almost invisible.
Uses setInterval, so it doesn't break slow browsers and always works.
Pure JavaScript, does not require HTML5 history, works everywhere.
Unobtrusive, simple, and plays well with other code.
Does not use unbeforeunload which interrupts user with modal dialog.
It just works without fuss.
Note: some of the other solutions use onbeforeunload. Please do not use onbeforeunload for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.
How It Works
Executes on page load
Saves your original hash (if one is in the URL).
Sequentially appends #/noop/{1..10} to the hash
Restores the original hash
That's it. No further messing around, no background event monitoring, nothing else.
Use It In One Second
To deploy, just add this anywhere on your page or in your JavaScript code:
<script>
/* Break back button */
window.onload = function(){
var i = 0;
var previous_hash = window.location.hash;
var x = setInterval(function(){
i++;
window.location.hash = "/noop/" + i;
if (i==10){
clearInterval(x);
window.location.hash = previous_hash;
}
}, 10);
}
</script>
In a modern browser this seems to work:
// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
if (confirm('Go back?')) {
window.history.back()
} else {
window.history.forward()
setTimeout(() => {
window.addEventListener('popstate', popHandler, {once: true})
}, 50) // delay needed since the above is an async operation for some reason
}
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)
I had this problem with React (class component).
And I solved it easily:
componentDidMount() {
window.addEventListener("popstate", e => {
this.props.history.goForward();
}
}
I've used HashRouter from react-router-dom.
You simply cannot and should not do this. However, this might be helpful:
<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>
This works in my Google Chrome and Firefox.
This seems to have worked for us in disabling the back button on the browser, as well as the backspace button taking you back.
history.pushState(null, null, $(location).attr('href'));
window.addEventListener('popstate', function () {
history.pushState(null, null, $(location).attr('href'));
});
Just run code snippet right away and try going back
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
<script src="~/main.js" type="text/javascript"></script>
<script type="text/javascript">
window.history.forward();
function noBack() {
window.history.forward();
}
</script>
Try this to prevent the backspace button in Internet Explorer which by default acts as "Back":
<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8 ) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' &&
(
d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE' ||
d.type.toUpperCase() === 'EMAIL' ||
d.type.toUpperCase() === 'SEARCH' ||
d.type.toUpperCase() === 'DATE' )
) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
try {
document.addEventListener('keydown', function (e) {
if ((e.keyCode === 13)) {
//alert('Enter keydown');
e.stopPropagation();
e.preventDefault();
}
}, true);
}
catch (err) {
}
});
});
</script>
It's basically assigning the window's "onbeforeunload" event along with the ongoing document 'mouseenter' / 'mouseleave' events so the alert only triggers when clicks are outside the document scope (which then could be either the back or forward button of the browser)
$(document).on('mouseenter', function(e) {
window.onbeforeunload = null;
}
);
$(document).on('mouseleave', function(e) {
window.onbeforeunload = function() { return "You work will be lost."; };
}
);
Just set location.hash="Something". On pressing the back button, the hash will get removed from the URL, but the page won't go back.
This method is good for preventing going back accidentally, but for security purposes you should design your backend for preventing reanswering.
Some of the solutions here will not prevent a back event from occurring - they let a back event happen (and data held about the page in the browsers memory is lost) and then they play a forward event to try and hide the fact that a back event just happened. Which is unsuccessful if the page held transient state.
I wrote this solution for React (when react router is not being used), which is based on vrfvr's answer.
It will truly stop the back button from doing anything unless the user confirms a popup:
const onHashChange = useCallback(() => {
const confirm = window.confirm(
'Warning - going back will cause you to loose unsaved data. Really go back?',
);
window.removeEventListener('hashchange', onHashChange);
if (confirm) {
setTimeout(() => {
window.history.go(-1);
}, 1);
} else {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
}
}, []);
useEffect(() => {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
return () => {
window.removeEventListener('hashchange', onHashChange);
};
}, []);
I create one HTML page (index.html). I also create a one (mechanism.js) inside a script folder / directory. Then, I lay all my content inside of (index.html) using form, table, span, and div tags as needed. Now, here's the trick that will make back / forward do nothing!
First, the fact that you have only one page! Second, the use of JavaScript with span / div tags to hide and display content on the same page when needed via regular links!
Inside 'index.html':
<td width="89px" align="right" valign="top" style="letter-spacing:1px;">
<small>
<b>
IN
</b>
</small>
[ <span id="inCountSPN">0</span> ]
</td>
Inside 'mechanism.js':
function DisplayInTrafficTable()
{
var itmsCNT = 0;
var dsplyIn = "";
for (i=0; i<inTraffic.length; i++)
{
dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
}
document.getElementById('inOutSPN').innerHTML =
"" +
"<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" +
DateStamp() +
" - <small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" +
dsplyIn.toUpperCase() +
"</table>" +
"";
return document.getElementById('inOutSPN').innerHTML;
}
It looks hairy, but note the function names and calls, embedded HTML, and the span tag id calls. This was to show how you can inject different HTML into same span tag on same page! How can Back/Forward affect this design? It cannot, because you are hiding objects and replacing others all on the same page!
How can we hide and display? Here goes:
Inside functions in ' mechanism.js ' as needed, use:
document.getElementById('textOverPic').style.display = "none"; //hide
document.getElementById('textOverPic').style.display = ""; //display
Inside ' index.html ' call functions through links:
<img src="images/someimage.jpg" alt="" />
<span class="textOverPic" id="textOverPic"></span>
and
Introduction
In my case this was a shopping order. So I disabled the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.
In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order was already submitted and redirected then too.
This code is full javascript.
Put this on your home page or whatever you need when someon goes back it brings them to the page they were previously on.
<script type="text/javascript">
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>

What would unhook my View and Controller from each other in Chrome and IE but not in Firefox?

I have previously successfully tested this MVC functionality in my app in Chrome but have recenlty also tested in IE (10) and Firefox.
When I mash the submit button on a page which sends model values to its controller for running a query and generating a report, it now works only in Firefox (each of the three browser indeed have their own peculiar characteristics -- where they shine or "dull" in relation to their cohorts (gleaming in purple and gold) -- but Chrome and Firefox seem to have lost the connection between the submit button's click handler and the corresponding Controller's method.
The app seems to simply hang after mashing the submit button in Chrome and IE; the breakpoints I have -- the first of which is at the very beginning of the corresponding [HttpPost] ActionResult in the Controller class -- are not reached. In fact, the app seems to freeze after mashing the button -- right-clicking the submit button after that does not give me an "inspect that element" in the context menu.
[HttpPost]
public ActionResult ReceiptCriteria(SalesReceiptCriteriaModel model)
{
if (ModelState.IsValid) // <-- there is a breakpoint here; only Firefox reaches it
{
. . .
In Firefox, it runs, and the breakpoints are hit.
What could possibly cause Chrome and IE to fail in this way, wheras Firefox soldiers on?
UPDATE
In response to Moby's request, here is the jQuery for the View in question:
The HTML in the View is pretty generic; the jQuery is:
$("#submit_button").click(function() {
// http://stackoverflow.com/questions/18192288/how-can-i-compare-date-time-values-using-the-jqueryui-datepicker-and-html5-time
var begD = $.datepicker.parseDate('mm/dd/yy', $('#BeginDate').val());
var endD = $.datepicker.parseDate('mm/dd/yy', $('#EndDate').val());
if (begD > endD) {
alert('Begin date must be before End date');
$('#BeginDate').focus();
return false;
}
else if (begD.toString() == endD.toString()) {
var dteString = begD.getFullYear() + "/" + (begD.getMonth() + 1) + "/" + begD.getDate();
var begT = new Date(dteString + " " + $('#BeginTime').val());
var endT = new Date(dteString + " " + $('#EndTime').val());
if (begT > endT) {
alert('Begin date must be before End date');
$('#BeginTime').focus();
return false;
}
}
$("#NumberOfResults").css("visibility", "visible");
$("#NumberOfResults").html("Please wait...");
EnableButton("submit_button", false);
// If all are selected, don't enumerate them; just set it at "All" (change of case, from 'all' to 'All', shows that the logic did execute)
var deptsList = $('#depts').checkedBoxes();
if (deptsList.length < deptsArray.length) {
$('#deptHeader span').html(deptsList.join(", "));
}
else if (deptsList.length == deptsArray.length) {
$('#deptHeader span').html("All");
}
// " "
var sitesList = $('#sites').checkedBoxes();
$('#sitesHeader span').html(sitesList.join(", "));
if (sitesList.length < sitesArray.length) {
$('#sitesHeader span').html(sitesList.join(", "));
}
else if (sitesList.length == sitesArray.length) {
$('#sitesHeader span').html("All");
}
$('#hiddenDepts').val(deptsList);
$('#hiddenSites').val(sitesList);
var UPCs = $('#UPC').val();
if (UPCs == "All") {
$('#UPC').val("1"); // take everything (1 and greater)
}
var resultsText = jQuery.trim($("#spanNumberOfResults").text());
if (resultsText != "") {
$("#NumberOfResults").css("visibility", "visible");
if (resultsText == "0") {
$("#NumberOfResults").css("color", "red");
} else {
var href = '/#ConfigurationManager.AppSettings["ThisApp"]/TLDCriteria/LoadReport';
var report_parms = {
GUID: "#Model.GUID",
SerialNumber: "#Model.SerialNumber",
ReportName: "#Model.ReportName"
};
window.open(href, "report_window", "resizable=1, width=850, left=" + (screen.width / 2 - 425));
}
}
}); // end of submit button click
function EnableButton(id, enable) {
if (enable) {
$("#" + id).removeAttr("disabled")
.removeClass("bottomButtonDisabled")
.removeClass("bottomButtonEnabled")
.addClass("bottomButtonEnabled");
} else {
$("#" + id).attr("disabled", "true")
.removeClass("bottomButtonDisabled")
.removeClass("bottomButtonEnabled")
.addClass("bottomButtonDisabled");
}
}
UPDATE 2
Something else which may or may not shed some light on this problem is my .js and .css references:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" type="text/javascript" defer > </script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript" defer> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript" defer> </script>
<script src="#Url.Content("~/Scripts/jquery-migrate-1.2.0.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/anytime.compressed.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/dynamicCheckboxes.js")" type="text/javascript" > </script>
. . .
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/dynamicCheckboxes.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/anytime.compressed.css")" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="/Scripts/html5shiv.js"> </script>
<![endif]-->
UPDATE 3
The Network tab in the Chrome Developer Tools looks like the middle of Wyoming (a whole lot of nothing), with a msg about the bottom informing me "No requests captured. Reload the page to see detailed information on the network activity."
When I dutifully mashed F5, it showed all the .js and .css files accessed, and finally (at the top), the page I'm gawking at. Mashing the "View Report" causes no more activity in the tab, though. I do see the console.log() msg I placed at the end of the submit button click handler, though, to wit: "made it to the end of submit button click"
There is one err msg in the console, too, but this:
Failed to load resource: the server responded with a status of 400 (Bad Request) http://localhost/%3C%=%20System.Configuration.ConfigurationManager.AppSettings[%22ThisApp%22]%20%%3E/Content/Images/SSCSsprite.png
Would simply fail to load the resource, not wreak other mayhem, right?
UPDATE 4
Based on Simon Halsey's hint, I found that, on stepping though the jQuery in Chrome, it fails this test:
if (resultsText != "") {
...obviously it's not in Firefox, and I assume that it also fails in IE (I'll czech to be sure in both cases, and update this).
Later: It's "" in Firefox, too...and the first time through, it also failed-wouldn't continue on. Second time through, it got through, though...???
There is two options:
There is no request due to javascript error
Your request signature doesnt math controller method
A.
Browsers have different behaivior with some javascript functions. Thats one of the reasons why jQuery is so popular.
The most efficient way to find it is to debug javascript line by line in each browser.
Likely it is the reason.
B.
Also your javascript is quite exotic for me. I guess you are catching sumbit button click and modifying inputs values on a fly.
I would recommend to use $.post or $.ajax and preventDefault instead.
It would make your javascript more clear and simple.
C.
To analyze what requests are sent from your browser I would recommend to use fiddler.
http://fiddler2.com/

Absolute paths to Trigger.io assets?

We're building a Trigger app with Chaplin underneath. It would be nice, for development purposes, if we could use absolute paths to our assets, a la:
<link rel="stylesheet" href="/_forge/stylesheets/app.css">
<script src="/_forge/javascripts/vendor.js"></script>
<script src="/_forge/javascripts/app.js"></script>
Is it possible to do this in Trigger?
Unfortunately different platforms have different URLs on Trigger (due to them having their own features and limitations).
If you want to get absolute paths you can use the file module and do something along the lines of:
forge.file.getLocal("js/app.js", function (file) {
forge.file.URL(file, function (url) {
$('body').append('<script src="'+url+'"></script>');
});
});
I'm not sure why an absolute path is useful though, I would recommend only using one html page (index.html) as navigating to a new page is slower on the phone than changing the dom using javascript. In which case all of your relative paths should always be the same.
The easiest thing might be to detect the whether or not forge is present in your index.html and load the javascript accordingly:
<script type="text/javascript">
function addScript(src, callback) {
var tag = document.createElement('script');
tag.type = 'text/javascript';
tag.src = src;
tag.onload = callback;
document.getElementsByTagName('head')[0].appendChild(tag);
}
var vendor = "javascripts/vendor.js";
var app = "javascripts/app.js";
if(window.forge === undefined) {
vendor = "/"+vendor;
app = "/"+app;
}
addScript(vendor, function() {
addScript(app, function() {
require('initialize');
});
});
</script>

Newline in Google spreadsheet not outputting in Google chart table

This code works perfectly except for a small formatting issue I can't find an easy way to fix. The google spreadsheet as the datasource has newline in the columns. However, in the table it looks as if they are simply formatted by spaces. I've tried using the allowHthml option in the data table (after converting the newlines to tags) but that then removes all formatting and makes the table look terrible. I've also tried the "Formatter" class but that seems more driven to concatenation of fields and also lives by the same no-html rule.
Anyone know of something i'm missing here that can get the newline to show properly in the table without breaking the formatting. I want to simply add the newlines into the fields so they display properly.
You can copy/paste this right into jsLint and it will run and show you what i'm talking about.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
var opts = {dataType:'jsonp'};
var query = new google.visualization.Query('https://docs.google.com/spreadsheet/pub?key=0AiEVKSSB6IaqdDZBTGJqV0lLZEV3YS0teXZkOWR4M3c&output=html', opts);
query.setQuery("select * ");
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Create and populate the data table.
var data = response.getDataTable();
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
​
This may be a bit of a hacky solution but how about using a JavaScript method to replace all line breaks in a string with <br /> tags? I also added a small amount of CSS so that the new table has bottom vertical alignment (like the original Spreadsheet would have).
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
var opts = {dataType:'jsonp'};
var query = new google.visualization.Query('https://docs.google.com/spreadsheet/pub?key=0AiEVKSSB6IaqdDZBTGJqV0lLZEV3YS0teXZkOWR4M3c&output=html', opts);
query.setQuery("select * ");
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Create and populate the data table.
var data = new google.visualization.DataTable(
response.getDataTable().toJSON().split("\\n").join("<br />"));
var opts = {'allowHtml': true};
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, opts);
}
google.setOnLoadCallback(drawVisualization);
</script>
<style type="text/css">
.google-visualization-table-td{
vertical-align: bottom;
}
</style>
<div id="table"></div>

Phonegap and jquery mobile : a href -> Origin null is not allowed by Access-Control-Allow-Origin

Im trying to use jquery mobile with phonegap, in a multi-page document.
Tring to use basic href links within the document, gives the Origin null is not allowed by Access-Control-Allow-Origin error which is quite annoying.
This is because the index page is refered to via file:// rather than http:// which webkit interprets as origin null. Has anyone got jquery mobile and phonegap to work in a multi page environment? if so how can you do it? If you add rel=external to the href tags the links work, but of course all the transitions are lost.
Cant find any info on this specific problem on stack overflow or teh internetz.
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
$(document).bind( "mobileinit", function(){
//alert("mobileinit fired");
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript">
function onDeviceReady() {
navigator.network.isReachable("google.com", reachableCallback, {});
}
// Check network status
function reachableCallback(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
if (networkState != 0) online = true;
}
var online = navigator.onLine || false;
$(document).ready(function() {
$(document).bind('deviceready', function(){
onDeviceReady()
})
// Your main code
})
//Now if you about to make an AJAX call to load up some dynamic data, you can easily check to see if you're online
if(online) {
} else {
}
</script>
</head>
<body>
<h1>Welcome to PhoneGap</h1>
Edit html
</body>
</html>
Here's the official documentation on how to do just what you are looking for...
Hope this helps!
Leon's comment is the correct answer - you need to add rel="external" to static links.
To Test
Download mongoose http server
copy mongoose_xxxxxxx.exe file to your assets/www
Now you can design your html pages for jquery mobile without Access-Control-Allow-Origin
I think you can find the solution here: http://view.jquerymobile.com/master/demos/faq/how-configure-phonegap-cordova.php
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
$.mobile.phonegapNavigationEnabled = true
Although I have not gotten it to work, I think that here are the solution.
if you are targeting app above JELLY_BEAN(API Level 16), here is what you can add to MainActivity class.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
super.appView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
Which will allow null origin XHR requests.

Resources