acess session in view (javascript) from the controller - javascript

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.

Related

Passing Parameter though html server pages using '#'

I am trying to pass a variable through an HTML page, and I got it working, but when I changed to a server, the HTML pages go from 'page1.html' to 'page1#' After this change I can no longer send parameters to my second page as they come out as 'undefined'. The passing of the variable works, it's just retrieving it.
The URL looks like this: http://localhost:1337/page1#?34
Here is the old working code on that no longer works:
// Takes parameters from HTML address and passes it through
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(0);
var queries = queryString.split("&");
var placeHolder = queries[0];
var Final = parseFloat(placeHolder)
I want to extract the number 34 from the URL and store it in a JS variable.
Thanks in advance for any advice
I'm not getting your point if you want some data from one page to another, so you can use localstorage for example
//index1.html
<script>
localStorage.setItem("item1", 34)
</script>
//index2.html
localStorage.getItem("item1")
var item = localStorage.getItem("item1");
</script>

How can I pass smarty variable to .js file for var definition?

I have in php getting id from server request for parameter id
$id = $_REQUEST['id'];
$smarty->assign('id', $id);
And in the smarty .tpl display files {$id} outputs the number to the client browser.
I need this variable in the javascript for the page:
var id = {$id};
I use id later in the javascript to define datatables default search value.
"oSearch": {"sSearch": offer_id},
My problem is I need to properly pass the id to the javascript, if is set at all. Right now it displays {$id}. Any ideas, please?
In your template (.tpl) file, include the code
<script>
var id = {$id};
console.log(id); // for debugging purposes
</script>
In your browser's Javascript console, you should be able to see the value of id.

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.

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

Categories

Resources