Node js setup an Anchor [duplicate] - javascript

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

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.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

passing value from one page to another with javascript

How can I pass the value of textarea to a new page according to the groupwall method?
Here I just redirect the page. I want to make status update according to their semester.
Here is my code. Give me some code sample or suggest if this is not the right way to do that.
<form action="" method="get">
<textarea name="status" id="wall" cols="50" rows="2">
</textarea>
<input name="submit" type="submit" value="share" onclick="groupwall();"/>
</form>
<script type="text/javascript">
function groupwall(){
var semster=document.getElementById('txtsamp').value;
if(semster == "4-1"){
window.location ='4-1hpage.php';
//header("location: member-index.php");
}
else if(semster =="3-1"){
window.location ='3-1hpage.php';
}
else if(semster == "2-1"){
window.location ='2-1hpage.php';
}
else {
window.location ='1-1hpage.php';
}
}
</script>
you might be better off posting the textarea content to your server and storing it somewhere, even in the session. the reason I say this is that while you could pass it in window.location as a GET parameter, the textarea content can be arbitrarily long and might be too long to be passed as a GET parameter. you might consider an AJAX request to post the textarea to the content, perhaps performing validation, before redirecting to the next page of your application.
Just give your form an id -
<form id="share-form" ...
Set the action of the form instead of redirecting
var share_form = document.getElementById('share-form');
share_form.action = '....';
Submit the form
share_form.submit();
1) do a form post to another PHP page and
a) Store it in a database (If you will really use this in future also)
OR
b) Store it in Session Variable
OR
2) do an ajax post to a server page and
OR
a) Store it in a database
OR
b) Store it in Session Variable
Then from any PHP pages you can access these values.
Send as a parameter through the query string yoururl.com?variable=value
Through $_SESSION environment variable
Using a cookie (if turned on)
AJAX - store in database or text file before leaving page, and retrieve when entering new page
The simplest way to pass some sort of variable to a new page if the data isn't large is to put it in a query string in the URL and then have the new page parse it out of there and act on it. A query string is the part of the URL that follows a question mark like this:
4-1hpage.php?data=whatever
The query string values don't affect which page is called on your server, but can be used by either server or client to trigger different behavior in that page.
In the specifics of your particular question, it doesn't seem like you need to pass any data to the next page because you're already called a different page based on the results of the textarea, but you could pass the value like this if you needed to:
function groupwall() {
var semster=document.getElementById('txtsamp').value;
var url;
if(semster == "4-1") {
url ='4-1hpage.php';
} else if(semster =="3-1") {
url ='3-1hpage.php';
} else if(semster == "2-1") {
url ='2-1hpage.php';
} else {
url ='1-1hpage.php';
}
// encode the data for URL safety and make sure it isn't too long
window.location = url + "?semster=" + encodeURIComponent(semster.slice(0, 128));
}
If the textarea can be arbitrarily long and it needs to be capable of accepting very long values, then you will want to post it to your server and let the server decide where to redirect the user after the form post. When generating a new page, the server can then populate that page with whatever content is needed based on the values in the form post.
Other places that data can be stored temporarily so a future page can access it are cookies and HTML5 local storage. Cookies are somewhat restricted in size and it isn't efficient to put large data into cookies. HTML5 local storage isn't supported in all browsers so you generally need an alternate strategy as a fallback.

I replace HTML using javascript, but that contains a form, want to keep value of that form

I have a page that I have a page I pull from the server every x seconds using some ajax, and then I replace some HTML on the site with the new HTML pulled from the server. The problem has always been that there is a form in that HTML. I want to know is there a way to preserve the value of the form (that the user has entered) when replacing the html in javascript.
Use two callback functions (you should use $.ajax), in the callback before sending (beforeSend(x){ /your code here/; }) you save the parameters (to an array or hashtable): saved = $(element).val(); then in the second callback (use success(x){}) you write them back in. using $(element).val(saved);
var save = document.getElementById('userForm').value;
//replace HTML
document.getElementById('userForm').value = save;
Two ways,
Send and then replace the value in the HTML on the server
Using JavaScript, save it in a session: http://www.webreference.com/authoring/languages/html/HTML5-Client-Side/
I'd say the best solution would be to combine the two and save a session on the server, then load it each time you load the HTML.
-Sunjay03

passing value to JSP via javaScript

boolean canModify = UTIL.hasSecurity("PFTMODFY") && something;
function name() {
I need to pass a value false to something when the page loads.
}
window.onLoad = name
How can i pass a value from JavaScript to JSP on the page load
I think you mean it the other way around, have server-side code output a value that JavaScript can see at page-load time.
Sending from your server code (JSP) to your client code (JavaScript)
Just output it like you would anything else, e.g.:
<%
boolean canModify = UTIL.hasSecurity("PFTMODFY") && something;
%>
var canModify = <%=canModify%>;
// ^ ^
// | +-- server-side variable
// +-- client-side variable
When the JSP actually runs, the script code returned to the client will simply be
var canModify = false;
or
var canModify = true;
That's a boolean; if you need to output a string, you need to put the quotes around it and be careful that you escape anything within it that should be escaped inside a JavaScript literal string (like a backslash, for instance, and whatever quote character you're using).
Sending from your client code (JavaScript) to your server code (JSP)
But if you really mean you want to send a value back to the server on page load (which seems odd, but hey), you'd have to use Ajax for that. If you're going to be doing Ajax stuff, I'd recommend using a library like jQuery, Closure, Prototype, YUI, or any of several others as they can dramatically simplify the process for you. For instance, using jQuery, this client-side code sends a value back to the server:
jQuery.get("/your/page/url", {"name": "value"});
(or jQuery.post for things that make changes). Using Prototype, it'd be:
new Ajax.Request("/your/page/url", {
method: "GET", // or, of couse, "POST"
parameters: {"name": "value"}
});
All of the libs I mentioned above have similarly easy-to-use mechanisms for sending data to the server. Note that this mechanism is bound by the Same Origin Policy.
You don't need a library for this, of course — anything a library can do, you can do yourself. The features I've listed above are all wrappers for the XMLHttpRequest object (Wikipedia, MSDN, MDC). See the linked resources for examples.
Non-Ajax hack
I shouldn't have said you need to use Ajax for this, more like you want to. :-) If, for some reason, you really didn't want to use Ajax you could do it by adding something to the page with JavaScript that triggers a retrieval from the server, and then include your value as a flag in that request. For instance:
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.src = "/path/to/jsp?name=" + encodeURIComponent(value);
document.getElementsByTagName('head')[0].appendChild(link);
Your JSP would do whatever it needs to do with the query string, and then return anything that's valid in a stylesheet (/* */, for instance). Or if you don't want to use a style sheet link, use an img tag and return a transparent pixel; etc.
But I wouldn't do that. I'd use Ajax.

Categories

Resources