How to access javascript variable in .net master page - javascript

I need to enable a script which is present in a .net master page, in only selected html pages that use this master page. can this be achieved by declaring a variable in javascript of html pages where I need this script and set the variable to some value, so that I can enable the scripts in master page only when variable is NotNullorEmpty? Does some one know if this works. If so how to get javascript variable in html, in to .net master page ?

There are 2 ways I can think of.
The first if to assign the variable to a hidden input field. Which can be accessed in the Request.Form.
html
<input type="hidden" value="your value" name="Hidden1" id="Hidden1"/>
javascript
document.getElementById('Hidden1').value = "an other value";
C#
var myValue = Request.Form["Hidden1"];
The second is saving the variable into a cookie which can be accessed in Request.Cookies.
var myValue = Response.Cookies["Cookie1"].Value;

The most flexible form of this that I have seen is to render a JSON object directly to the page as script (adding any other script you might need also), then making the javascript code fill in a hidden field with JSON data on form submit for the server to parse.
Here are the basic steps:
Create an empty hidden field for the server to read when the client submits, but send it to the client empty.
Create a string which is the script and JSON data you need to send to the client. (Use the JavaScriptSerializer .NET class.)
Fill a LiteralControl with the script tag and its contents. (This works well in the OnPreRender step, but you can do it elsewhere.)
Include JSON2.js (it's all over the web - get it from a trusted source)
Write javascript code to fill the hidden field on submit, using JSON2.stringify() to push any javascript object into that field.
On the server, you can again use JavaScriptSerializer to read the values from the submitted object.

What you are basically wanting to do is test for javascript.
There are a few ways to do this, but I would use both a server-side and client-side cookie.
In your global.asax's onbeginrequest, test for a server-side cookie of "js-test-s"
Cookie Exists, check for "js-test-c"
"js-test-c" Cookie Exists, JS enabled
"js-test-c" No Cookie, JS disabled
Cookie doesn't exist...
Set the "js-test-s" cookie
output a simple html document...
[html]
[head]
[meta refresh tag set to 1 second /]
[script to set "js-test-c" cookie, then force refresh /]
[/head]
[body][/body]
[html]
Browser will refresh the request with one or both cookies set.
WARNING: You may want to store the original request details, and redirect to another location in case cookies are disabled.

I might be not understanding the question correctly but as far as I can tell the easiest way to do this is by creating a property on the master page and then setting it on all pages that need to execute the script:
In Master page
public bool EnableScript
{
set
{
if (value == true)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "startup", "alert('test');", true);
}
}
}
In all pages that need to run javascript that use the current master page:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.EnableScript = true;
}
If you have to output your JavaScript on every page, even on the once that don't execute it (why?) then just add it as a function and then inside your property add a code to call that function, and set your property to true on all pages that require JavaScript to execute.

Related

How to assign values from form to Javascript session variables

I am trying to create Javascript Session variables that will read information from one form and pass these variables to another form.
I can assign strings to these Session variables but i cannot assign values from Form elements to these variables
function SetUserName()
{
<% var text1= "Charles";%>
<%Session["UserName"] =text1;%>
var session_value='<%=Session["UserName"]%>';
}
</script>
This is the Javascript on the first page which works and on a button click i call another page where i can display this Session Variable.
function LoadUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username);
}
This gets called on load of second page. How can i pass values from HTML elements to the Session Variable?
For Example Say i have a Text Box
<asp:TextBox ID="Address_Box" runat="server" TextMode="MultiLine"
MaxLength="200" ></asp:TextBox>
How can I send the text from this box to the session variable?
Your code:
var session_value='<%=Session["UserName"]%>';
does not "access the ASP.Net session from javascript".
With this code you do generate (during the processing of the request) some text that will be sent to the browser. This text contains the string that results from the expression Session["UserName"].
Once this text arrives at the browser it is interpreted as javascript. This javascript has no knowledge of any session values or the fact that it was (partly) generated.
You need to find some way to send data from the browser back to the server (using postback or ajax, for instance) before it can be stored in Session.
You would have to put this somewhere in your c# code.
Session["UserName"] = Address_Box.Text;
For a more complete answer I'd have to see more of your code. For a better solution you'd have to explain what you're trying to achieve

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax request is run...If it is not I want the user to be redirected to a separate page where the variable is set.
for example I want something like this:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
So the first time the page is run, it checks if the variable is set. If the variable is not set it will set the variable and then reload the page and run through the check again.
Problem is 'accessKey' always returns undefined but the code runs through as if the variable is defined. Why?
If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again
There is your problem: variables (or any other piece of js code) do not persist between page reloads.
If you need stuff to persist, you have to use one of these:
Server-side sessions or databases (using ajax to pass data to the server and persist it there)
Client-side storage (such as localStorage).
Cookies (can be generated at client-side or server-side)
Save the value in hiddenfields or in cookie.

How to read the value of variable in JS in the scope of JSP on the same page?

I have a JSP page in which third party sign-in plugin is used, which is JS. After sign-in is successful, the user-id obtained in JS has to be used in JSP to maintain session by storing that value.
For this, I tried 'manipulating' jQuery but that works only if the JS value is a literal or is pre-known. But here in this case, value is fetched at runtime as per sign in.
Also tried <% String s = "<script>document.writeln(var)</script>"; %>
But again the above problem. works only when value is known before hand.
document.getElementById("ppurl").innerHTML = ppurl; prints the value. But I want to store it.
So, how to achieve the purpose of passing a variable's value in JS to JSP?
Assuming your third party sign-in plugin is client-side JavaScript:
Remember that the JavaScript runs when the page reaches the client. The JSP code has long since completed and so is no longer in the picture.
You have three options that I can immediately see:
Send the data to the server using Ajax or similar.
Refresh the page (sending the login data to the server as part of the refresh).
Update whatever it is on the page that you want to have this value in it via the DOM.
#1 and #2 should be fairly self-explanatory.
For #3: Say you have various forms on the page and you want to make sure that the login token or whatever it is you get from the client-side plugin gets sent with the form using a hidden field in the form with the name tokenField. You could do this:
function putTokenOnForms(token) {
var forms, index, form;
forms = document.getElementsByTagName("form");
for (index = 0; index < forms.length; ++index) {
form = forms[index];
if (form.tokenField) {
form.tokenField.value = token;
}
}
}
You can do much the same with links in a elements (adding to the href property of each link that goes back to your server), etc.
The page outputting the JavaScript to the client cannot read data back from that JavaScript.
You need to initiate a new HTTP request (e.g. using XMLHttpRequest or setting location.href) that passes the data back to the server and then read it in (e.g. from the query string or POST data).
Store it in a cookie using JS. Read it back in JSP.
In your JS, after you get the userID, you can do:
document.cookie = 'myuserid='+userID;
In your JSP, you can read it back like:
Cookie[] cookies = request.getCookies();
String userID;
for(int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("myuserid")) {
userID = c.getValue(); // c.getValue() will return the userID
break;
}
}

Create a javascript msgbox (YES/NO) and get results in code-behind

Is it possible to create a (yes/no) javascript messagebox from code-behind, and also retrieve the return values?
I would like to set the content of a session object based on the client Yes/No.
The idea is to use this approach for redirecting iphone clients from my default web page.
"Do you want to go the iphone version of this site?"
--YES Redirect to "iphone" default page, and set a session object to avoid asking this question again if default page is requested again
within the lifespan of the session object.
--NO Set a session object to avoid asking this question again if default page is requested again within the lifespan of the session
object.
Just display the message and set an appropiate cookie. Then make your server-side react to the cookie and render the selected version of the site.
http://www.htmlite.com/JS006.php - Javascript Confirm popup
http://www.w3schools.com/js/js_cookies.asp - Javascript cookies
In Code behind on FormLoad or wherever it best suits your needs, you would just have to set your button's OnClientClick as follows:
button.OnClientClick = "IphoneVersion()";
In Markup create a function in javascript as follows:
function IphoneVersion() {
if (confirm('Do you want to go the iphone version of this site?')) {
//set hidden value here }
else { //don't set hidden value }
}
You can set your Hidden control value to yes/no text and refer to it behind code or you can redirect in the function itself.
That will do it!
Or you could stash the value in a hidden field and read it on the server side.
** EDIT **
OP Comment:
I would like to set the content of a session object based on the client Yes/No.
Either way you look at it, if he wants to set this value in session, he has to go back to the server.
Try something like this:
confirmSomething = function(){
__doPostBack("<%=Button1.ClientID%>", confirm("Are you sure?"));
}
<asp:Button ID="Button1" runat="server" OnClientClick="confirmSomething();" />
Code-behind:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
bool conf = bool.Parse(eventArgument);
}

How to get the title of a link using JavaScript

I want to get the title of a webpage without opening it, i.e. without using window.open().
I basically want to check whether the page i am providing the link for exists or an error is returned.
What I am trying is checking for similar links. Here is the code
(I want to know when to break out of this loop, i.e. at what point the link I am writing exists).
document.getElementById("TOI").innerHTML="<p>";
if (month<10) var m="0"+month;
else var m=month;
for(var i=1;;i++){
alert("ji");
var a="http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf";
alert(a);
var link=window.open(a);
window.focus();
alert(link.location);
alert(link.document.title);
if(link.document.title!="The page cannot be found"){
link.close();
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<a href='http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf' target=_blank>Page "+i+"</a> ";
}
else{link.close();break;}
}
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<\p>";
}
See to check if a url exists or not, you must use a server-side scripting language. Javascript is client-side and can't access server. So, first of all make a server side script (maybe php) that returns the status of url that you wanna check. Then from javascript side, use an ajax call to get the result of that script. That way you can check your url array, if all of them exists or not.
var attribute = element.getAttribute("title");
I want to get title of a webpage
without opening it(that is without
using window.open()) I basically want
to check whether the page i am
providing the link for exists or an
error is returned
Just because a page has a title doesn't mean it exists.
http://www.google.com/thispagedoesnotexist.htm
Examine HTTP status codes rather than page titles:
Can Prototype or JQuery return an HTTP status code on an AJAX request

Categories