Assigning Session variable from Javascript - javascript

Hi all I am assigning a Session variable using Javascript as follows, I am using devexpress controls
<script type="text/javascript">
function f() {
var v = textBox1.GetValue();
<%Session["Demo"] = v;%>
var sValue='<%=Session["Demo"]%>';
textBox3.SetValue(sValue);
}
</script>
This is giving an error on webpage when I run as The name 'v' does not exist in the current context
So can some one help me what to do

As #The New Idiot mentioned - it cannot be done on a client side, since Session objects are stored on a server side. The only way you can do it is on some request get/post or even ajax request and set variable on a server side

Related

How to display a global javascript variable in typo3 using typoscript?

I would like to output a global variable "elemenId" that is created by a javascript in typo3.
The javascript writes the ID of the touched html element in the global variable elementId:
document.addEventListener("touchstart", (e) => {
// get elementId of touched element and save as global variable elementId for further processing
window.elementId = e.target.id;
});
I would like to display the elementId value in typo3.
Is there any chance to access this variable in typo3 using typoscript? Something like:
lib.global_variable = COA_INT
lib.global_variable {
20 = TEXT
20.data = GP : elementId
}
Is there any other way to achieve that?
Thanks a lot for your help!
What do you mean with global variable elementId?
global in what context? PHP? javascript? TYPO3?
You need to distinguish between server(webserver with PHP/TYPO3) and client(Browser with javascript).
How can data be exchanged?
Anything in PHP can be written in the rendering process. The output is HTML, including CSS and javascript. Alternatively TYPO3/PHP can generate other formats like JSON, XML, PDF or CSV.
In this way PHP can transfer some information to Javascript by generating a piece of javascript which assigns the value to a (global) javascript variable:
$output = '<script>js_var = "' . $php_var . '";</script>';
echo $output;
Now the client/browser can use the value by executing this javascript code.
On the other hand any value from your client/browser can only be transferred to the server/PHP by doing a new server request. This can be done with a new page request with arguments (either POST or GET) and the server can respond with a appropriate reaction.
Or you do an AJAX call and you will get a appropriate response and some javascript can insert the response in the current document.
Another option would be that javascript only acts locally in the browser and used the information available to generate or modify the current HTML-document. that might be showing the ID of any clicked HTML element in a special HTML object.

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);

Add variable from session to another session using ajax

I am new to JavaScript and and trying to pass a session variable from 'Name' which has a variable already assigned using PHP and pass it into 'cartItem' upon button click.
To my knowledge the current code stores the value of 'Name' into var item then requests HTML to the server to return and update the session variable 'cartItem' with the value stored in var item.
Button and script:
<button id='addToCart' onclick='addToCart'>Add to cart</button>
<script>
function addToCart(){
var item = sessionStorage.getItem('Name');
item = new XMLHttpRequest();
item.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
sessionStorage.setItem('cartItem', item);
}
}
}
</script>
cartItem is then displayed in my navbar using a function which is called across all pages
<span class='item-info'>
<span>" . $_SESSION['cartItem'] . "</span>
</span>
But it does not show. Any advice would be greatly received.
You have created an XMLHttpRequest object but have not opened a URL or sent the request.
Example (not tested):
var name = sessionStorage.getItem('Name');
var item = new XMLHttpRequest();
item.open("GET", "http://www.example.com/endpoint/" + name);
item.send();
After this, the object "item" will contain information such as the response body and HTTP status code.
If I understand correctly, you are using a sessionStorage object to store PHP session variable values on the Javascript / HTML document, correct? If so, then understand that when you try to change a value, you are only changing it on the client side, the server side (or PHP side) remains unaffected).
It looks like you have the right idea with the XMLHttpRequest, but in order to get done what you need to do, you'll need to make a PHP script which the Javascript function will ajax to. Here's a little mockup:
<?php
//NOTE: this does not do any input sanatation
//name of this script is changeVal.php
$keyAr = ["Name","Price","Value","Other"];
if (in_array($_POST['key'],$keyAr) {
$_SESSION[$_POST['key']] = $_POST['val'];
}
I am intentionally using an array in this manner rather than $_SESSION[$_POST['key']] so that a potential hacker can't change the value of ANY session variable.
Once you have the script above, you can make an ajax request onto that script, where key is the name of the var to change and val is the value to change it to.
NOTE: this does not perform any sanatation or protection for the input material. This is just a simple mockup.

Pre-set javascript variables from URL parameters

Imagine I have a script abc.js, which has one global variable userid. Several AJAX requests are made instantly after it is loaded (it can happen after or before DOM is parsed by browser). I need the script to have different variable value for different users. Requests has to be made instantaneously after JS is available. Here is what I am looking for:
Browser makes a request to /js/abc.js?userid=12345
Server parses userid=12345 and adds userid = 12345 to the script
Server returns the script to user
Browser parses the script and userid is set to 12345, then everything is processed normally.
Is there a way to do this with some Apache/Lighttpd extension? Since I can't rely on <script>userid=12345</script> at the begining of the document, as abc.js will most probably be executed before userid=12345 is evaluated.
You can simply use PHP to output the javascript variables at a point before when the abc.js script is called. In this case the parameter would be passed to the main PHP script (i.e the page). Like this:
<script type="text/javascript">
var userid = <?php echo $_GET['userid']; ?>;
</script>
<script type="text/javascript" src="/js/abc.js">
Of course you probably want to sanitize the parameter value in PHP before using it.
Here, abc.js can just reference the value of userid in global scope. There is no need to pass userid to the script in URL and have Apache use PHP to dynamically generate the js file. In fact, you likely don't want that approach as it prevents optimal browser caching of the script.
If you don't want PHP involved you have other options to pass this data such as the URI parsing option presented by #yent, HTML5 localStorage, cookies, etc.
You can parse window.location.search and set window properties :
var p = window.location.search.substr(1).split(/&/);
if(p.length && p[0]) for(var i=0; i<p.length; i++) {
var a = p[i].split(/=/);
window[a[0]] = a[1];
}

how to pass javascript variable to embedded Server Side code ASP.NET WebForm

let say i have a function like below in BAL.cs file
public static void xyz(string name)
{
Response.Write("Hello "+name);
}
Let say i have a javascript variable x.
now i want to call the function from BAL.aspx file
<script>
var x= "Tahmid";
<%=BAL.xyz()%> // want to pass x as a parameter
</script>
this is in webform.
It seems like there is some sort of confussion here that I would like to help solve. Server code and client code are separated. When client code executes (such as javascript) the server has no way to know what happened so your server side code (code behind) is not aware of any changes. In order to have the javascript variable information on the code behind you'll need to send that variable value back to the server and one of the mechanisms is the one provided by user2952502. I think in your case a postBack (using a submit or link button) would be more appropiate, right? I think you're trying to redraw the page based on something that the user did (since you're using javascript).
I think we should have some more information to understand the whole scope of your question and probably suggest you a better way to deal with it.
so you want to use windowfunctioname ?
since javascript is clientside and asp is serverside you could create a list of calls with parameters.
<script type="text/javascript">
var calls = [{exec: 'functionname', param : {name: 'Tahmid'}}];
document.addEventListener('DOMContentLoaded', function () {
c = calls.length;
for (var i = 0; i < c; i++) {
call = calls[i];
window[call.exec](call.param);
}
});
</script>
I hope that was an answer that helps.
The question is not clear enough .
what are u trying to do ?
just to print a dynamic text u can do with javascript function..
if u have to use a server function please specify the platform u use : MVC / WebForms..
in MVC you can use jQuery Post:
<script>
var x = "value";
$.post('#Url.Action("Action","Controller")',{name : x});
</script>

Categories

Resources