How can I access Session variables in code-behind - javascript

In script I set Session.
<script>
$(document).on('click', '.Pagination', function () {
'<%Session["Pagination"] = "' + $(this).attr('id') + '"; %>';
alert('<%=Session["Pagination"] %>');
});
</script>
Alert works.
I can't access When i want to session from code-behind
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Val = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
String Val equal to ' + $(this).attr('id') + '

I used to put the value in the hidden variable and this will be accessible in code-behind, anyway the session object is active in code behind you can set the variable to session successfully.
Advantage:
Globally declared session strings are accessible in code-behind and you can use the variables by calling the property files
ASP
<asp:HiddenField id="session_obejct" runat="server" />
Javascript
document.getElementById('session_obejct').value = "Variable you want to set in session";
C#
session["SESSION_NAME"] = session_obejct.Value;
you can use other methods as well, I hope this will meet your requirement

I used this way and do it if one have better way pleas tell me
Javascript function:
<script>
$(document).on('click', '.Pagination', function () {
PageMethods.NumPagination($(this).attr('id'));
});
</script>
Code behind :
[System.Web.Services.WebMethod]
public static string NumPagination(string Num)
{
Page Pagination = new Page();
Pagination.Session["Pagination"] = Num;
return Num;
}
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Select = "1";
Select = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
LINK

You cannot write to the (server-side) Session from within client side code.
The alert('<%=Session["Pagination"] %>'); works because it is executed server side first, reading the value of Session["Pagination"] and inserting that into the javascript source, before sending that source to the browser.
By the time the browser sees that text and interprets it as javascript, the server-side commands (<% ... %>) have been replaced. The browser wouldn't know what to do with them anyway.

Related

Access server side variable in javascript/jquery in asp.net

I am working on asp.net web forms application.I need to access datatable returning from database in javascript/jquery.
But problem is that I am not able to get value. I tried declaring it on top of class as well as as session but didn't work.
I am getting blank if I try to alert it.
Here is my code..
On page load.. there are nested methods which are being used to load data inside GridView. Now I want to get same data in client side as well so that I can use to show in on Google map..
On Page_load event my below is code to get data from database
this.gvGmap.DataSource = null;
GmapDataTable = GetDataTable("someparameter to get data from db");
Session["GmapDataTable"] = GmapDataTable;
this.gvGmap.DataSource = GmapDataTable;
this.gvGmap.DataBind();
Now I tried two different approach to get this data client side.. but it's blank
1st
var mJSVariable = <%:GmapDataTable %>;
alert(mJSVariable);
2nd session approach
var yourVariable = '<%= Session["GmapDataTable"] %>';
alert(yourVariable);
If you data is just linked with your current page and not huge then use viewstate instead of session this will not create much load on your server. Instead of accessing session directly in client side assign it to a property this will make your code more reuseable.You can searilize your data table.View State Vs session
Although using session you can do with the following way.
`public static DataTable GmapDataTableProperty
{
set { HttpContext.Current.Session["GmapDataTable"] = value; }
get
{
if (HttpContext.Current.Session["GmapDataTable"] != null)
{
return (DataTable)HttpContext.Current.Session["GmapDataTable"];
}
return null;
}
}
GmapDataTableProperty = GmapDataTable; `
Access it on client side like
var mJSVariable = <%= GmapDataTableProperty %
your approach via session is right, but you need to convert your session object into DataTable object, make sure your session variable is not null.
var myValue = '<%= ((System.Data.DataTable)Session["dt"]).Rows[0][0] %>';
alert(myValue);

How can I access my Javascript Variables in PHP?

I have a file called lightstatuspage.php and within it, I have HTML, JavaScript and PHP code. I have used some variables within the JavaScript part of the code and I am trying to send these variables to the server by passing them to the PHP part of the code. However, this is not working.
I am using $.post("lightstatuspage.php", slider_val); and then in the PHP part, I am calling the variable by doing $_GET['rangeslider_val'];.
What am I doing wrong and what can I do differently to get the variable from JavaScript and send it to the server?
function show_value(x)
{
document.getElementById("slider_value").innerHTML=x;
event.preventDefault();
var slider_val = x;
var query = new Parse.Query(Post);
query.first({
success: function(objects){
objects.set("slider_val", slider_val);
objects.setACL(new Parse.ACL(Parse.User.current()));
return objects.save();
window.location.href = "lightstatuspage.php?rangeslider_val=" + slider_val;
}
})
}
The PHP code is:
<?php
$_GET['rangeslider_val'];
print($rangeslider_val);
?>
First Add Jquery
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
to the end of page before closing body tag.
To send Javascript variable to PHP. the best way is to use Ajax. and add the following code to your javascript.
Do not forget that the below code should be on an event. For example on a button click or something like that
$( document ).ready(function() {
var x = $('#input1').val();
//or var x= 15;
$.post("lightstatuspage.php",
{
'rangeslider_val': x
},
function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
// you can show alert or not
});
});
and in php, you can use:
$value = $_POST['field1'];
now your variable is in $value in php.
P.S:
Backend Page and HTML page should be on same domain or you have to check Cross-Origin Resource Sharing
Second Solution
as the User accepted this solution here would be the code:
$.get("lightstatuspage.php?rangeslider_val=" + slider_val,function(res) {
console.log(res);
});
the second way is only the difference between POST and GET method
Third Solution
if you don't want to use Jquery in your project and you need pure javascript you can use below code
var str = "Send me to PHP";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "lightstatuspage.php?rangeslider_val=" + str, true);
xmlhttp.send();
Change the order of the last 2 lines of your JS function. You are returning from the function before changing the page's location.
you forgot to store variable on print
<?php
$rangeslider_val = $_GET['rangeslider_val'];
print($rangeslider_val);
?>
You call $_GET but you don't assign the value to the variable $rangeslider_val in PHP and you are returning in JavaScript before calling the PHP script. Also you mentioned that you want to use $.post from clentside if you do it this way you have to use PHP $_POST to get it from there.

Javascript Variable to C#

I have a question about getting Javascript Variables from a local PC JS File to a Local C# Program.
I'm writing a C# Program for the PC which needs some Variables from a Webpage which is locally located on my PC with just HTML CSS and JS which is displayed in a webview function in my C# Form.
Now I'm reading a Value from the User in my "Webpage" and want to pass this variables to my C# Code so I can use this variables further.
There are at least two ways to get any variable from a browser to your backend. One is to Post a form that contains the variable. The other is to make an AJAX call to send the variable data to some backend service. The AJAX call would, in most cases, be the way to go since no screen refresh is done and involves no interaction or initiation from the user.
use below code :
HTML and Javascript :
<head runat="server">
<title></title>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
Code Behind :
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
More information :
C# functions returns a value and show in webpage

javascript function not taking arguments

This question is probably more complex than I realize.
When the page loads, it checks for a cookie (usercookie). If it exists, it calls a function in an external .js file. This function is situated in a jquery file and does three things. It hides come stuff, sets a variable (userloggedin) to true, and displays a welcome message to the users. However, its acting very strange. In order for the function to work, I have to define it with a "new" before it like its an object. If I don't do that, it won't work at all. But if I use it, it refuses to take any arguments. Take a look.
Keep in mind that this is situated in a $(document).ready(function() {}
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}
Here is how I call the function from the main document.
<script type="text/javascript" id="cookiescript">
//checks for the usercookie and gets the value as well
var query = true;
if (query === true)
{
cookievalue =
"Seth";
userlogged(cookievalue);
}
</script>
Some of this code was returned from a php query to mysql, but I know that code works fine.
So my question is, how do I create this universal function in the js file that I can call anytime a user logs in somehow (eg. cookie detected, form entry)?
You have to declare a parameter at the declaration part like
function functionname(parameter)
you need to change the method signature to accept a parameter
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}

How do you set a session variable in JavaScript?

Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?
Sounds like you need cookies, localStorage, or sessionStorage.
You can use JS to change the values in a hidden field, and capture them on the postback, which personally I think preferable to cookie usage if the value is only needed for the life of the current session.
It's a very bad idea to do this with PageMethods.
You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.
Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.
You can also get a session value that way.
Like this:
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string item = context.Request.QueryString["item"] ?? "";
string update = context.Request.QueryString["update"] ?? "";
switch (item)
{
case "A":
if (!string.IsNullOrEmpty(update))
context.Session["A"] = update
object a = context.Session["A"];
context.Response.Write(a != null ? (string) a : "none");
break;
case "B":
if (!string.IsNullOrEmpty(update))
context.Session["B"] = update
object b = context.Session["B"];
context.Response.Write(b != null ? (string) b : "none");
break;
}
}
public bool IsReusable
{
get { return false; }
}
}
See my post here for XMLhttpRequest:
Why does this JavaScript code ignore the timeout?
You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.
I like to do it the following way:
javascript:
function SendData(data) {
var postbackarg = "#####" + data;
__doPostBack("txtTest", postbackarg);
}
VB In Page_Load event:
If Me.IsPostBack Then
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim args As String = Request.Params.Get("__EVENTARGUMENT")
ProcessUserInterfaceData(controlName, args)
If (controlName = "txtTest" AndAlso args.IndexOf("#####") = 0) Then
args = args.Substring(5, args.Length - 5)
'args now = data from the UI
End If
End If
This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '#' is to identify the postback as coming from SendData.
Session variables cannot be set using Javascript directly
But you can use the following code to set session variables in aspx page
<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>
You can check the same variable using an alert in javascript
alert('<%=Session["SESSION VARIABLE NAME"] %>');
Yes session variable can be set using Pagemethods using the below way
declare the below code in aspx.cs page
[WebMethod]
public static void functionname(string st)
{
Home h = new Home();
System.Web.HttpContext.Current.Session["SessionUserName"] = st;
h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
}
and call the function using pagemethod in aspx
PageMethods.functionname("HELLO");
this will set the session variable to HELLO
You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!

Categories

Resources