change model value in javascript - javascript

For example I've got model attribute curPage on my jsp page.
How to change its value in javascript function?
Something like this
function prev() {
var curPage = '${curPage}'; //get value
if (curPage > 1)
curPage--; //modify it
'${curPage}' = curPage;
}

JavaScript is executed on the client side, while the model attributes exist on your server.
In case of your example above, the ${curPage} will be replaced with the value of $curPage at runtime and the javascript would be sent to your client. Any modifications you make to the curPage variable will stay on the client side.
If you want to persist this change to your server, you need to make some kind of web request back to the server(ajax, form submit etc.)

Related

Connection between Java and Javascript through ZK framework

I have been facing an issue with the communication between java and javascript through zk framework in a iframe.
In simple words, I want to save a string in the current session and access it (or even overwrite it) in javascript.
my java lines:
HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
session.setAttribute("key","testing");
my zul lines:
<iframe id = "change_option" src="select_one_option.html" scrolling="no" width="700px" height="400px" > </iframe>
my javascript lines in the html file:
var session= /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false; //finds the correct session id + desktop name?
session = session.substring(0, session.indexOf('.')); //removes desktop name and keeps just the session id in a string
//another try
console.log("Saved: " + sessionStorage.getItem("key")); //returns "Saved: null"
//another try
var username = '<%= Session["key"] =%>'
console.log ( " Variable is : " + username) //returns "<%= Session["key"] %"
Since the html file is big I thought it would be better to do it through iframe and not try to rewrite inside the zul file. Any suggestion is highly appreciated.
There are a few approaches you can consider depending on your full requirement.
#1 The page located inside of the iframe and the outer page may communicate directly, using the window postMessage API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
This require a bit of setting up, but allows the page located in the iframe to post an event to the parent page. The event has a data field, which you can use to transfer data.
The parent page can subscribe to such event, and read the event data.
With this method, you don't actually need to write stuff to the session at server-side, since this communication happen fully at client-side.
This is good if the server doesn't care about knowing the value.
#2 saving the object in session from the inner page, using it from the outer page
You are already setting the session attribute in the native session:
HttpSession session = (HttpSession)(Executions.getCurrent()).getDesktop().getSession().getNativeSession();
session.setAttribute("key","testing");
Note that session attributes are Java-side only. They are not automatically returned to the client as cookies.
You can add a cookie with the same value to your response, if you want to handle this by cookies:
https://www.zkoss.org/wiki/ZK_Developer%27s_Reference/UI_Patterns/Communication/Inter-Application_Communication#Use_Cookie
However, this is a bit overkill because ZK is a communication framework and you can already pass the value to the outer zul page in a number of ways.
First, you can just execute arbitrary JS on the page using the Clients#evalJavascript method.
https://www.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Useful_Java_Utilities#evalJavaScript
With that, you can just build a JS call containing your value retrieved at server side, and execute it in client. Should look like this:
String myValue = ... //retrieve your server-side value;
Clients.evalJavascript("myClientSideFunction('"+myValue+"')"); //executed in an execution of the zul page.
But you can also use that value as a client-attribute, pass it as a component value, etc.
There are a lot of arbitrary things you can do to pass that value back to the client, all with pros and cons.
For example, if you want to put that value back into a textbox, you can simply use the textbox#setValue method. It really depends on what you are looking to achieve.

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.

How can i write JavaScript between server side code in razor view?

Eg.
$(".button").click(function () {
var index=$(this).closest('tr').index();
var records=#Model.Task[index];
});
In this,index is javascript and #Model.Task is server side so error say "The name index does not exist in the current context".
Before on click function, you should do below.
var tasks = JSON.parse('#Html.Raw(Model.Task)');
After then you can do
$(".button").click(function () {
var index=$(this).closest('tr').index();
var records = tasks[index];
});
as it was told by vivek and Andrei - it is impossible. index is variable from javascript, and Model.Task is array from model. they are executed in different moment. think about it that way. All values obtained from Model are executed/parsed by server before sending response to client (browser). it means that client sees them as normal text, not as an object. But javascript is executed on client (browser) AFTER page was downloaded and rendered (and the code you provided is executed even later - after button was clicked). This means that when Model is parsed it has "no idea" about javascript.
the only way to do what you want to do is what KnowGe posted - save all Model.Task table as javascript object and then use this object in your listener

Node js setup an Anchor [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

Set Session value using Javascript and retrieving the same using razor umbraco

I have written following code let say in Page 1
<a Onclick="setSessionValue()" href="page2"></a>
<script type="text/javascript">
function setSessionValue()
{
var selectedCarNoideId = "1026";
'<%Session["BannerNoideID"] = "'+ selectedCarNoideId +'";%>'
alert('<%=Session["BannerNoideID"]%>');
}
</script>
And now retrieving session value on other page (Scripting File .chtml) using following code.
<h2>Session-:#Session["BannerNoideID"] </h2>;
In the Page 1 alert PopUp displays "1026" as session value
But In Page 2 tag display following value as a output of session .
"Session-:'+ selectedCarNoideId +'"
Am I missing any thing ?
You're mixing javascript and server-side code in such a way that the javascript isn't being evaluatd as you expect.
The Server side session variable is literally being set to '+ selectedCarNoideId +' as the page is being rendered. Javascript in this case is doing nothing to set the session value.
Although why you're getting the alert message to display 1026 is anyone's guess - is the BannerNoideID session variable being set elsewhere as well perhaps?
If you're trying to save a variable generated client-side with Javascript in the session on the server, you will need to submit it.
One way to do it would be to create a simple MVC Controller (WebAPI by default is sessionless) and then POST the value to it using Ajax or a form post.
Alternatively, you could pass the id through on the QueryString to the next page or something like that - that approach is probably the simplest.
Without knowing more about your setup, workflow and business logic I can't really suggest much more.

Categories

Resources