Managing Html text in popup - javascript

I'm using OpenLayer popup.
when initializing it, there a parameter required to contain the html displayed in the popup.
this parameter is javascript string.
I have a conflict, on the one hand the html text is long so I prefer to place it in html file and read the file to the variable.
On the other hand, the html depends on other local variables, so if I leave it on its place I can concatenate some strings and local variables to compose the final variable containing the html text. but it is very long and ugly code...
Maybe experienced javascript programmers can help me to find a design solution to this problem?
thanks

As you are using OpenLayers you can use the OpenLayers.loadURL function to retrieve HTML from your server.
http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Ajax-js.html
If you want to pass in local variables to server side HTML you can set up a simple handler that accepts variables, and integrates these into some static HTML (using string formatting or a template).
If you are using .NET then a .ashx file can do this. See http://dotnetperls.com/ashx for an example.

Another solution is to use an Ajax request to load your file, and then print the content inside the popup.
Using JQuery:
$.get('myfile.php',function(content){
var popup = new OpenLayers.Popup("popupid",
new OpenLayers.LonLat(mouseX,mouseY),
new OpenLayers.Size(360,200),
content,
true);
map.addPopup(popup);
});
When the Ajax request is completed, you can create the popup and fill it with the file content previously loaded.

I would recommend geographikas solution, and also try to use different js-classes to improve maintainability and readability. Don't do everything in the same object, make your own popup object that inherits from or uses OpenLayers.Popup.Anchored or something, and make the Ajax server call from there. This way you won't clutter your other code with this. Also makes it easy to reuse and substitute when needed.
I would go for something like this (untested!):
mynamespace.mypopup = function(o) {
var size = new OpenLayer.Size(100, 70);
var icon = new OpenLayers.Icon(); // Fill it
var popup = new OpenLayers.Popup.Anchored(o.id, o.lonlat, size, getContent(), icon, false, null);
var getContent = function() {
// ajax call
// return a string
}
return popup;
}
in a file called "mypopup.js"
and call it with:
var popup = new mynamespace.mypopup({id: 'whatever', lonlat: myLonLat});

Related

MVC 5 - How to send an Excel file to the client?

I have a Bootstrap application that shows a list of data. I have a button at the bottom of the page that, when clicked, creates an Excel file and sends it back to the client.
The link (button) the user clicks to start the process is as follows:
<li>Export list to Excel</li>
The JavaScript function that gets called looks like this:
function ExportToExcel() {
var Url = "/UserLocation/ExportToExcel";
$.get(Url);
}
I know this probably isn't right, but it does correctly call my C# function that creates the Excel spreadsheet.
My C# function looks like this:
public ActionResult ExportToExcel()
{
var locationList = this.UserLocationData.GetList(this.AccountRowId).AsEnumerable();
ExcelPackage package = Common.Excel.CreateExcelFile(locationList);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = "ExcelTest.xlsx",
// Always prompt the user for downloading, set to true if you want the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(package.GetAsByteArray(), "application/force-download");
}
At the moment, when the user clicks the button, my C# function is called, but nothing is returned to the client. I suspect my JS function is not correct, but I don't really know what to do to make it correct. I also don't know what MIME type to use in my C# method (the last line in my C# method). Is there a better way to do all this? I am fairly new to JavaScript.
With $.get() you're getting the data through ajax. The browser will get the file content in the ajax response, but there is no way to offer the user to save this data as a file. (Well, technically is possible in most browsers, but not in all of them, although some more are supported with this js. But obviously it's overkill for this case. Thanks to zerkms for his comment).
The solution is much simpler, use the old good window.open(url), so the file is opened in a new browser window, and the user will be invited to open or save it (that depends on the browser configuration).
Or use directly a link like this:
<li><a href ="/UserLocation/ExportToExcel" class="btn btn-info btn-sm">
Export list to Excel</a></li>
(unless your js function does some extra processing).

Use an imported object (from the servlet) inside a script tag

My servlet sends to the JSP page an object. This object has some attributes and depending on these attributes i want to change the color during a hover action. One solution is to change the hover style directly in my JSP page. But i was wondering, can i use somehow this object inside the script tag and take the decisions from there? I found this but it didn't work (or i use it a wrong way)!
<script>
$(document).ready(function() {
//import myObject;
});
</script>
Your JSP gets rendered on the server and sent to the client. The client (browser) does not know anything about your Java/JSP code.
But, you can render properties of your Java object into the rendered page, like:
<script>
var stringVariable = "${myObject.myStringProperty}";
var intVariable = ${myObject.myIntProperty};
</script>
This will be rendered on your server, and the browser will see it like:
<script>
var stringVariable = "Hello World!";
var intVariable = 4711;
</script>
Using this technique, you can use your server side variables on the client, wherever you need them (HTML, CSS, Javascript).

Store very small amount of data with javascript

I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.

How to override variable parameter loaded from another script

I have a script that loads the code dynamically. It is kind of a search engine. When I press a search button, the action gets triggered and a new page opens with many parameters.
I want to override one of the parameters generated with the script in the new URL. JS code is quite big and hard to read, but I have found the important part in the Firebug DOM editor.
This is the pattern of the URL generated when you perform the search:
http://www.example.com/...?ParameterOne=123&ParameterTwo=Two&ThisParameter=Sth&ParameterFour=Four...
What I want to edit is "ThisParameter" and change its value. This is the part edited in the DOM that does what I want:
Foobar = {
_options: [],
...
var options = {"ParameterOne":123,"ParameterTwo":"Two","ThisParameter":"ABC","ParameterFour":Four,...}
...
And this is the output of "ThisParameter" when you choose "Copy path" in Firebug's DOM tab:
_options[0].ThisParameter
I am wondering it this is possible at all. What makes me think that it is, is the fact that I can change this parameter in Firebug and it works perfectly. So, if Firebug can edit it, there should be a way to influence it with another script.
Looking forward to any suggestions, thank you in advance!
Since you cannot edit the dynamic script you have the following options:
You have to try to give the script the correct input and hope it uses your value.
Add a script to the results page which will read the url and arguments, change it and redirect, as we discussed here. (If you put everything in functions it should not conflict with the dynamic script if the functions are uniquely named.)
You could try adding something like this jQuery code to the page with the search button:
$('input[name=search_button_name]').click(function(e) {
e.preventDefault();
var form_search = $('#search_form_id');
$('<input>').attr({
type: 'hidden',
name: 'ThisParameter',
value: 'SomethingElse'
}).appendTo(form_search);
f.submit();
});
You can override any js function and method, or wrap you code around it. The easiest thing would be to look at the code you get and once it gets loaded, you re-declare a method with your own functionality.
I you are trying to replace a parameter in a specific jquery request, you can even wrap around the jquerys ajax method:
var jquery_ajax = $.ajax
$.ajax = function(options){
// parse only a specific occurence
if(options.url.indexOf("example.com") > -1) {
// change the url/params object - depending on where the parameter is
options.params.ThisParameter = "My Custom value"
}
// call the original jquery ajax function
jquery_ajax(options);
}
But it would be a lot cleaner to override the method that builds the ajax request rather than the ajax request itself.
I would investigate further on the scope of the variable options (var options), is it global? i.e. if you type 'options' in the Firebug console, does it display its properties?
If so, you could then access it via your own script and change is value, e.g.
options.ThisParameter = 'my-own-value';
You might hook your script to the click event of the search button.
I hope this helps, it could be more specific maybe if you have some sample code somewhere.

Javascript variable to html page 'script tag'

Is it possible, if one has a javascript variable like this:
var myVariable = "alert('BAM! It works!');"
to send it to an html page that has a script tag in, in other words, looks like this:
<script id="theScriptTag"></script>
and by 'sending' I mean going like this in the Javascript file:
getElementById("theScriptTag").innerHTML = myVariable;
Now maybe people normally don't do this. If there's another way to get a Javascript variable to an HTML page please don't hessitate to tell. It's difficult for me to explain why I would like to do it like this, only that I need to do it like this.
Thanks in advance!
EDIT...
From all the comments I can see this is some serious bad practice. Let me give you the over view and 'bigger picture' here... On the very same HTML page there is a form, and a div. Now right after a user fills out the form and submits it, it goes to the server and 'custom javascript' is generated depending on the variable the user selected. This custom javascript is then intended to go back to the client and execute. When it executes is creates/fills up a div element that then contains a google charts table (thus needed to get generated server side). The JS that needs to be executed looks like this:
var sendAttemptsChartTableData, sendAttemptsChartTable;
google.load('visualization', '1', {packages:['table']})
google.setOnLoadCallback(drawTable);
function drawTable() {
sendAttemptsChartTableData = new google.visualization.DataTable();
sendAttemptsChartTableData.addColumn('string','smsGuid')
sendAttemptsChartTableData.addColumn('string','attemptNo')
sendAttemptsChartTableData.addColumn('string','response')
sendAttemptsChartTableData.addColumn('string','error')
sendAttemptsChartTableData.addRows(1)
sendAttemptsChartTableData.setCell(0,0,'092A49AA-E2EF-46D3-A83E-0932B17B649A')
sendAttemptsChartTableData.setCell(0,1,'1')
sendAttemptsChartTableData.setCell(0,2,'<aatsms><submitresult action="enqueued" key="2066317199" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317200" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317201" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317202" result="1" number="0833756610"/></aatsms>')
sendAttemptsChartTableData.setCell(0,3,'')
sendAttemptsChartTable = new google.visualization.Table(document.getElementById('sendAttemptsTable'));
var view = new google.visualization.DataView(sendAttemptsChartTableData);
sendAttemptsChartTable.draw(view, {showRowNumber: true, allowHtml:false});
google.visualization.events.addListener(sendAttemptsChartTable, 'select', smsSearchHandler);
}
Based on your edit I understand your form sumbission results in a custom script. Would a JSONP-like solution work? Basically you can create a script tag in your current document, pointing its source to a server side script that processes the form and returns the code.
A basic example:
function getScript(){
/**process form, generate params**/
var nwScript = document.createElement('script');
nwScript.src = '/myscriptsrc/somescript.php?'+[generated parameters];
document.body.appendChild(nwScript);
}
If your goal is to execute the javascript code contained in the string, you can use the following :
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
What you are trying to do is essentially this:
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
eval takes the string you provide and "evaluates" the content - it executes the javascript stuff you provide in the string. Normally you want to do this with input from the user.
But this is considered bad habit, because:
it is slow
it is unsecure
Usually you can go another way, so you don't need to use eval. In most cases this is cleaner, faster and more secure.
Perhaps you could tell, WHAT you are trying to achieve, and then we can find a better solution.

Categories

Resources