How to give dynamic query parameter in <script> src? - javascript

I am building a simple asp.net application and in my aspx page I want to reference a script with dynamic query parameter.
For example:
<script src="../javascript/script.js?v=#var#" type="text/javascript"></script>
In the above code script path can have different query parameter in place of #var#.
I have also tried following code to get the parameter value from code behind.
<script src="../javascript/script.js?v=<%# myVar %>" type="text/javascript"></script>
but, here <%# myVar %> returns blank value. If I use = instead of # then it works perfectly if I add the script reference at the bottom of the page.
But, it only works if I reference the script at the bottom of page. otherwise it will throw the error.
"The Controls collection cannot be modified because the control contains code blocks (i.e. `<%= %>`)."
Now, my question is, "Is there any other way to do the same?"

I am assuming you are using ASP.net not MVC. I have tried this with ASP.net and done this by code behind approach you can create your script tag by code behind like below:
protected void Page_Load(object sender, EventArgs e) {
string jScriptValidator;
jScriptValidator = "<script type='text/javascript' src='../javascript/script.js?v=#123'></script>"; // your dynamic script tag with dynamic parameter
Page.RegisterStartupScript("key", jScriptValidator);
}
and result is follows:
Hope it helps you.

Related

Execute Javascript only on page load, not PostBack (SharePoint)

I'm trying to execute some JavaScript on page load on a custom page on a SharePoint site (it populates the people picker with the current user). The problem is that the code executes on postback too, which I don't want as it will reset any changes to the people picker.
I've tried using if(!IsPostBack) to no avail. Everything errors out at that point, giving
SCRIPT5009: 'IsPostBack' is undefined.
I can't find anything online to help with this. Any ideas? Thanks
You can create a function like this:
function IsPostBack() {
var ret = '<%= Page.IsPostBack%>' == 'True';
return ret;
}
IsPostBack is not a javascript variable, it's a .NET webforms variable that is only available on the server so the client will complain about it. So what to do then? I suggest this mish-mash in your control's html:
<% if(IsPostBack) { %> <!-- runs on server -->
<script type="text/javascript">
alert('will only be printed to html if not postback');
</script>
<% } %> <!-- ends server if-block -->
You may want to try the below. Use the JavaScript pageLoad method and use the isInAsyncPostBack Property of the PageRequestManager object to determine whether it's a postback. Refer the MSDN link here for more details.
<script type="text/javascript" language="javascript">
function pageLoad(sender, args) {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
// call you JavaScript function in here
}
}
</script>

Calling JavaScript function within a JSP page

I am trying to call a in-page JavaScript function from inside a JSP page. Here is the code snippet, but the JavaScript functions are not being called when the JSP page is rendered on the client. Anything wrong following this method of calling?
<% //more jsp code
if(count>0) { response.sendRedirect("main.jsp"); %>
<script type="text/javascript"> setCookie('user','<%=user1%>',1); </script>
<% } else { response.sendRedirect("index.jsp"); %>
<script type="text/javascript"> alert("please enter proper credentials and log in again"); </script>
<% } // more jsp code %>
You are attempting to send an HTTP redirect and output some HTML at the same time.
The HTML will appear on the page that will be displayed to browsers configured to not automatically follow redirects (which is practically none of them) so nobody is going to see the page which includes that HTML.
You need to put the HTML on the page you are redirecting to (or, in the case of the cookie setting code, set the cookie with JSP/HTTP instead of client side JavaScript).

How to call external JavaScript function in HTML

I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:
var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";
function scroll_messages()
{
for (var i = 0; i < Messages.length; i++)
document.write(Message[i]);
}
and in my HTML file 'Index.html' I am trying to call it like this:
<div id="logo">
<marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
<strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
</marquee>
</div>
The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:
<script src="Marq_Msg.js"></script>
in the 'head' tag with a separate call, that was a no go. I also tried instead using:
<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>
Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':
//Marq_Msg.js
function scroll_messages()
{
return "hello";
}
//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>
What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in the external script)
scroll_messages();
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page.
Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Result :
If anyone still has the reference error is probably because you are loading your Javascript with defer, or it's in the bottom of the body so when the function gets called your function still doesn't exist.

ASP.NET WebForms Routing Javascript Error

I have some problems with JavaScript using ASP.NET 4.0 WebForms Routing.
My code:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("GoodInfo", "catalog/good/{good}", "~/GoodInfo.aspx");
routes.MapPageRoute("GoodGroup", "catalog/group/{group}", "~/default.aspx");
}
With no routing everything is ok. But when I use it I got an error on hte page (in Firebug)
Error: jQuery is not defined
on this line:
jQuery(document).ready(function () {
HideBlocks();
});
So my JavaScript does not work on the page that was routed.
I added this line routes.Ignore("{resource}.axd/{*pathInfo}"); but it didn't helped me.
I have solved my problem! The solution consists of 2 parts.
Firstly I changed my scripts definition from
<script type="text/javascript" src="../scripts/something.js"></script>
to
<script type="text/javascript" src="/../scripts/something.js"></script>
Thanks MilkyWayJoe fot that solution.
Secondly I added Ignore Routing
routes.Ignore("catalog/good/{resource}.axd/{*pathInfo}");
instead of:
routes.Ignore("{resource}.axd/{*pathInfo}");
So my web resources have no more routes on pages like http://mysite.com/catalog/good/41
Also I have script events on the page like http://mysite.com/catalog/good/41/event/seq/1. To catch all parameters I add to my route rules this
routes.Ignore("catalog/good/{good}/{*query1}");
routes.Ignore("catalog/good/{good}/{query1}/{*query2}");
routes.Ignore("catalog/good/{good}/{query1}/{query2}/{*query3}");
routes.Ignore("catalog/good/{good}/{query1}/{query2}/{query3}/{*query4}");
And don't forget that your Ignore declarations must be placed before MapPageRoute declarations:
routes.Ignore("catalog/good/{resource}.axd/{*pathInfo}");
routes.MapPageRoute("GoodInfo", "catalog/good/{good}", "~/GoodInfo.aspx");`enter code here`
If you look at the generated source of your page, is the jQuery library included?
If you are including jQuery via a resource, double check that it is included and that it is before that line that errors.

Javascript loading but not running - rails 3.1

I have in my application layout file an external javascript file witch has several lines of code and at the end runs a function like BooManager.init() no big deal...
the problem is, it is not running the inside code on this javascript file.
this is how i use it:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "iphone4s, apple";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<%= javascript_include_tag "http://widgets.boo-box.com/javascripts/embed.js" %>
but it didn`t do anything it was suposed to do...
i`ve tried in simple html file and it works... what am i doing wrong?
NOTE:
the default way in html is this:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "keywords, between, commas";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
-- EDIT --
the result generated by rails:
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
It's not evaluating the script when loading using the <%= method. I'm not familiar with that syntax, but from the effect, that's what it sounds like. It's treating the script as html rather than code.
jQuery has a script load function that will get a script dynamically from a URL and then eval() it to execute it.
UPDATED WITH SAMPLE CODE
Add jQuery to your app:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
Then use it to load your script:
$.getScript('http://widgets.boo-box.com/javascripts/embed.js');
UPDATE NUMBER 2
I was able to duplicate the problem in this fiddle: http://jsfiddle.net/7x2zT/4/
If what you are trying to accomplish is to get your parameters activated before the script shows the widget - the default one looks like a sidebar, whereas your parameters make it more of a banner, then just make sure you put your parameters above the <script src stuff.
If you must be able to load dynamically, then you're going to have to figure out where the bug lies in the embed code, or if there's some other activation method. That site's documentation doesn't seem to be in English, so I can't help with that.

Categories

Resources