Include JavaScript in Perl-CGI generated page - javascript

I was trying to add a java-script to a page which is generated on the fly.
I tried this, but it seems like it is not working.
<SCRIPT SRC=\"sorttable.js\"></SCRIPT>
I always have to inline javacode along with the html for it to work.
Any clues ?

qq() is the equivalent of "", but with matching delimiters. It is going to be your friend if you are outputing HTML or JavaScript.
print qq(<script type="text/javascript">alert("The world is my oyster");</script>);
Note that you don't have to use () as delimiters, see perlop.
If you are outputting JavaScript that is building HTML, you should be using jQuery or Ext. But either way you will be in the multiple-levels-of-escaping-hell. JSON::XS might make your life less painful. Also learn about here-documents:
my $js = <<'JS';
alert( 'The world is my oyster' );
var $href = "example.html";
document.write( 'clicky' );
JS
print qq(<script type="text/javascript">$js</script>);
The tricky bit about the above is that $href is a JavaScript variable, not a Perl variable. (Yes, JS identifiers may include $.)

Perhaps this link might be helpful:
http://perlmeme.org/tutorials/cgi_form.html
It provides method of embedding a jsp function into the form-onsubmit as follow:
print $q->start_form(
-name => 'main_form',
-method => 'GET',
-enctype => &CGI::URL_ENCODED,
-onsubmit => 'return javascript:validation_function()',
-action => '/where/your/form/gets/sent', );
And there is a following link from Perl5 CGI library - support for Javascript, it's about linking javascript function to an event.
http://cpansearch.perl.org/src/MARKSTOS/CGI.pm-3.60/cgi_docs.html#javascripting
Regards

Well it depends on your quoting structure for the WHOLE thing. If you're printing this out in a uninterpolated heredoc, then \" just creates a bigger problem.
print <<'END_HTML';
...
<SCRIPT SRC=\"sorttable.js\"></SCRIPT>
...
END_HTML
or a q expression:
print q~
...
<SCRIPT SRC=\"sorttable.js\"></SCRIPT>
...
~;
So you would have to show more of your context. But let me assure you: when I write out the tags the right way, my JavaScript files gets sourced into the page, just as I would expect.

Related

Question mark in script breaks html

I have inserted a block of javascript in then body of a Joomla 2.5 article.
What I want to achieve is to open a default client email engine in order to send some information there.
The code looks like this:
var sendForm = function() {
...
window.open('mailto:admin#admin.com?subject=mailSubject&body=mailBody');
};
What happens actually, when I load the page is that whatever is after the "?" is broken and appears as plain text in the UI.
For example, I have the following stuff in the UI:
?subject=mailSubject&body=mailBody'); }; window.onload = getTotal();
What is wrong? Can you help me to spot the stuff that I am doing it wrong?
Thanks
It seems that this is a Joomla specific problem. I managed to get over it by using the {emailcloak=off}syntax before the actual email address.
Therefore the code looks like this mailto:{emailcloak=off}some#email.com?subject....
You might want to use ? instead of ?, and & instead of &. If you wish, you can refer to the HTML character numbers and names here.
It will not only solve your problem, but also pass the W3C validator.

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

How to generate a pure JavaScript file with Jade

I know that Jade is for producing HTML instead of JavaScript, but for a project I'm working, it would be great, and a huge time saver, if I could do this without adding a pipe in every line:
| (function(){
| //Some JavaScript Code
| var foo="#{bar}";
| console.log("This a JavaScript file generated with Jade");
| })()
The idea is to use the output of this template as the source of a regular JavaScript include like this:
<script type="application/javascript" src="foo.generated.js"></script>
So doing something like this:
script(type="application/javascript").
(function(){
//Some JavaScript Code
var foo="#{bar}";
console.log("This a JavaScript file generated with Jade");
})()
won't solve my issue, because I need to output pure JavaScript with no DOM container element.
Is there another way to do this without adding pipes to every line? Or I have to assume that Jade was designed to produce only HTML, give up, and find other solution without Jade?
Thanks in advance!
Produce all XML, include HTML. And jade was not designed to cast large blocks of javascript. The best thing you can do is create a method for obtaining these large blocks, and modifying variables. As it is doing in Example.
I think you should use:
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.end(`(function(){
//Some JavaScript Code
var foo="${bar}";
console.log("This a JavaScript file generated with Jade");
})()`);

Transferring javascript from a view to a seperate JS file

I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>

ruby nokogiri restclient to scrape javascript variable

I'm using restclient and nokogiri to parse some html which works great, but there is one piece of information stored in a js (jquery) variable which I need to return and I'm not sure how to parse it. I can use Nokogiri to parse the javascript block, but I need one subset of it which is probably simple but I'm not sure how to do it. I could probably regex it but I'm assuming there's an easier way to just ask for it using JS.
#resource = RestClient.get 'http://example.com'
doc = Nokogiri::HTML(#resource)
doc.css('script').each do |script|
puts script.content
end
What I'm trying to get:
<script type="text/javascript">
$(function(){
//this is it
$.Somenamespace.theCurrency = 'EUR';
//a lot more stuff
not sure if that fits, but you could retrieve it as follows:
irb(main):017:0>
string
=> "<script type=\"text/javascript\"> $(function(){$.Somenamespace.theCurrency = \"EUR\"}); "
irb(main):018:0>
string.scan(/\$\.Somenamespace\.(.*)}\);/)
=> [["theCurrency = \"EUR\""]]
Nokogiri is an XML and HTML parser. It doesn't parse the CDATA or text content of nodes, but it can give you the content, letting you use string parsing or regex to get at the data you want.
In the case of Javascript, if it's embedded in the page then you can get the text of the parent node. Often that is simple:
js = doc.at('script').text
if there is the usual <script> tag in the <head> block of the page. If there are multiple script tags you have to extend the accessor to retrieve the right node, then process away.
It gets more exciting when the scripts are loaded dynamically, but you can still get the data by parsing the URL from the script's src parameter, then retrieving it, and processing away again.
Sometimes Javascript is embedded in the links of other tags, but it's just another spin on the previous two methods to get the script and process it.

Categories

Resources