Jquery solution for loading a map from another .aspx? - javascript

Trying to achieve a Jquery print template (C# ASP.net) which gets my map from my Default.aspx and appends it to a print page (Print.htm) whereby I can edit the HTML. so far...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"</script>
<script type="text/javascript">
$(document).ready(function() {
$("#Printbtn").click(function() {
var mapObj = $("MapCell_Map1");
var mapHtmlStr = mapObj.html();
mapHtmlStr = mapHtmlStr.replace(/CURSOR: crosshair; /g, "");
mapHtmlStr = mapHtmlStr.replace("Maps['Map1'].pendingTiles.remove", "return;");
mapHtmlStr = mapHtmlStr.replace("Maps['Map1'].pendingTiles.remove", "return;");
mapHtmlStr = mapHtmlStr.replace("Maps['Map1'].pendingTiles.remove", "return;");
mapHtmlStr = mapHtmlStr.replace("Maps['Map1'].pendingTiles.remove", "return;");
mapHtmlStr = mapHtmlStr.replace("Maps['Map1'].keyFocus=true;", "");
$.ajax({url:"print.htm", context: document.body,
success: function(response){
var printDoc = $(response);
printDoc.find("#mapPanel").html(mapHtmlStr);
var pwin = window.open("Print.htm");
var pdoc = window.document.open();
pdoc.write(printDoc.html());
pdoc.close();
});
return false;
});
});
</script>
Doesn't fire, just posts back after the button click...
<asp:Button runat="server" id="Printbtn" Text="Print" Forecolor="white"/>
Print.htm page...
html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="MapPanel">
</div>
</body>
</html>

If the Html you want to add is static you could load a separate Html file into memory and then add the dynamic Html to the hidden div before writing contents to the new window
jQuery Example (Untested):
function printmap() {
var mapObj = $("#Map1");
var mapHtmlStr = mapObj.html();
// snip - do string replacements as shown in question
$.ajax({url:"print.html", context: document.body,
success: function(response){
var printDoc = $(response);
printDoc.find("#mapPanel").html(mapHtmlStr);
var pwin = window.open("#");
var pdoc = window.document.open();
pdoc.write(printDoc.html());
pdoc.close();
});
}
Further non-jQuery examples of loading Html File in Javascript are shown in this post:

Related

How to include external script into <script>?

Inside my JS function I need to add this:
< script src=https://xxxx.com/c3.js type="text/javascript" async defer>< /script>
How to edit the code the right way?
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
<script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
console.log(ab_id_transakce);
}
</script>
If I understand your question correctly, you are trying to add a script tag to the DOM. It seems that you are trying to add the HTML script tag in the Javascript function, which will not work. What you can try is:
Add the script tag directly in the HTML like this:
<script src=https://xxxx.com/c3.js type="text/javascript" async defer></script>
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
console.log(ab_id_transakce);
}
</script>
Add the script tag dynamically
<script>
function affilate() {
var ab_instance = "xxx.com";
var ab_kampan = 3;
var ab_cena = 1;
var ab_id_transakce = document.getElementById("email").value;
console.log(ab_id_transakce);
var script_tag = document.createElement("script");
script_tag.src = "https://xxxx.com/c3.js";
script_tag.type = "text/javascript";
script_tag.async = true;
script_tag.defer = true;
// in case you want to add the script tag to the <head>
document.head.appendChild(script_tag);
// in case you want to add the script tag to the <body>
document.body.appendChild(script_tag);
}
</script>

Function parameter is not being passed. How to correctly pass parameter into function of another JavaScript file?

I want to to call a function file2Function(getValue) of a file (page2.js) from another JavaScript File (page1.js) to open new page in browser and display some data on it using parameter passed viamyFunction1(e) into file2Function as file2Function(itemFromItems). So file2Function(getValue)should take value of var itemFromItems and should display on page2.html. But it is displaying "undefined" for getValue. Kindly help me finding out where I am doing Mistake. Thank You.
// page1.js
function file1Function()
{
var secPage1 = document.getElementById("page1Section");
var heading = document.createElement("h4");
var anchor= document.createElement('a');
anchor.setAttribute('href',"#");
anchor.innerText = "Click Me";
anchor.addEventListener("click", myFunction1);
heading.appendChild(anchor);
secPage1.appendChild(heading);
anchor.id=1;
function myFunction1(e) {
var itemFromItems = e.currentTarget.getAttribute("id");
console.log("item",itemFromItems);
file2Function(itemFromItems);
}
}
// page2.js
var globalVar;
function file2Function(getValue)
{
console.log("getValue",getValue);
window.open("page2.html");
// window.open("https://www.google.com/");
globalVar=getValue;
console.log("globalVarNow",globalVar);
}
function loadDynamicData()
{
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
<!-- page1.html -->
<!DOCTYPE html>
<html>
<head>
<script src="js/page1.js"></script>
<script src="js/page2.js"></script>
</head>
<body onload="file1Function()">
<h3>This is page1</h3>
<section id="page1Section">
</section>
<script>
</script>
</body>
</html>
<!-- page2.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="loadDynamicData()">
<h3>This is page2</h3>
<section id="page2Section">
</section>
<p id="paraId"></p>
<script src="js/page2.js"></script>
</body>
</html>
The problem is that globalVar is a global variable, but the value you are assigning to it in file2Function() is accessable only within its scope, that is why you are getting undefined, because loadDynamicData() has no access to the new value of globalVar.
You could call loadDynamicData() from file2Function() and pass getValue as an argument, but since you need to open page2 before executing loadDynamicData() it won't work.
What I suggest is you pass getValue along with your URL as a query parameter and get it from inside loadDynamicData(), it'll work fine.
SOLUTION:
function file2Function(getValue)
{
window.open("page2.html?value="+getValue);
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var url_string = window.location.href
var url = new URL(url_string);
var globalVar = url.searchParams.get("value");
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
If you want to hide the values you can use sessionStorage instead of query parameters:
function file2Function(getValue)
{
sessionStorage.setItem('value', getValue)
window.open("page2.html");
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var globalVar = sessionStorage.getItem('value')
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}

insert dynamically string containing script into HTML and executing it dynamically

I have a variable of the form :
var x = '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'
and I want to insert it with jquery into my HTML code and execute it.
I tried using the append, html and eval without any luck.
Any ideas?
sample script:
<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<img src="http://..." width="120" height="600" border="0" alt="">
</noscript>
this will in the end show an img, which will load asynchronously.
Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.
Here is a working fiddle:
https://jsfiddle.net/2vrfxrse/
Javascript
var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);
HTML
<script>executeTest();</script>
This solution will probably work for your specific scenario:
var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);
while (res) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(res[1]));
document.body.appendChild(s);
res = rx.exec(x);
}
JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output
You can use Jquery getScript:
//Moment example
if (typeof moment == "undefined") {
var url = "~/assets/js/moment.js";
$.getScript(url);
}
Or Jquery Function:
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Creating an option menu based on a text file?

I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");

google Custom Search api in a js file

First I found the demo in google doc:
<html>
<head>
<title>JSON/Atom Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
// handle result
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr">
</script>
</body>
</html>
And it works fine.
But know I want to trigger the "search process" inside a js file say mySearch.js, so how can I get this done ?
example:
var XXXLayer = cc.Layer.extend({
init:function () {
this._super();
var theUrl = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr';
// what to do here ???????
return true;
},
hndlr:function(response) {
// handle result
}
});
Any suggestion would be appreciated thanks :)
You could add a script element, when you trigger the search process.
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=KEY&q='+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}
using the code from #RamK, do the following:
index.html:
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="query"></div>
<script src="cs.js"></script>
</body>
</html>
cs.js:
var key = "your api key"; // API KEY
var id = "your custom search engine id"; // CSE ID
var q = "cats"; // QUERY
function hndlr(response) {
console.log(response); // a way to see your results
}
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = `https://www.googleapis.com/customsearch/v1?key=${key}&cx=${id}&q=${q}`+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}
triggersearch();

Categories