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

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

Related

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.

In javascript function calling var to another page through session or localstorage

Im to trying to send javascript response to another page by using localstorage or by using session but im unable to get response here is javascript fun below eg
page1.php
function data(responseData) {
alert(responseData.dataValue); eg:name //here im getting data
alert("Total = "+responseData.dataValue);
$("#submit-link").attr('href',"https://example.com/paymentdata.php?totalScore="+total);
}
page2.php
Here i called the link
<button id="process">Process</button>
<br />
links // i want that name here
I have tried i got nothing. All i want from page1.php data get in page2.php data i have tried through session also no result
By using the browser local storage you can pass any data between any pages in your website. If you have more complex data like an object you have to stringify/parse to get it to work, but otherwise a string or integer will work fine.
window.localStorage.setItem('key', 'a string value');
window.localStorage.setItem('key', JSON.stringify(YourValueAsObject));
var getValueFromLS = window.localStorage.getItem('key');
var getValueFromLSParsed = JSON.parse(getValueFromLS);

acess session in view (javascript) from the controller

This is my controller code. I want to get values stored in session in view(javascript code)
decimal.TryParse(permotion.PROMOTION_AMOUNT.ToString(), out promotionAmount);
int.TryParse(permotion.PROMOTION_TYPE_ID.ToString(CultureInfo.InvariantCulture),
out promotionTypeId);
Session["PromotionAmount"] = promotionAmount;
Session["TypeId"] = promotionTypeId;
view code is:
var amount='#Session["PromotionAmount"]';
var id='#Session["TypeId"]';
alert(amount)
alert(id)
but this java-script code is returning empty string. How I can retrieve session value in view? Thanks in advance.
You can put the values within a ViewModel / ViewData
ViewData["hdnFieldValue"] = "some value";
use a hidden string to store in the HTML
#Html.Hidden("hdnField", ViewData["hdnFieldValue"], new {#id = "hdnField"})
Then when document is loaded retrieve via JS
var myValue = document.GetElementById(hdnFieldValue)
No issue with that code. It will work fine. Which i am using in my page. Use Convert.ToString(Session["value"]). Even if its not working, check weather Session has value or not.

Sending and getting data via $.load jquery

I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/

Assigning Session variable from 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

Categories

Resources