How to display a page after a get request received? - javascript

I am trying to display a page after a get request received. For example, some user send a get request to my server, ('/home') and I want to display home page after that.
I tried res.render but it doesn't change the page. It only send url back.
fetch('lom').then((res)=>{
console.log(res);
}); //GET Request
app.get('/lom',(req,res)=>{
res.render('lom');
}); // Respond
I expect to see /home page after request but current page is not changing.
I don't want to use window.location.href = '/lom'. I want to change page in server side.

You're using fetch.
The entire point of using fetch is that the browser doesn't navigate to a new page, and the response is processed using JavaScript instead.
Use a regular link. Submit a form. Use window.location.href = '/lom' (I know you said you didn't want to, but not wanting to do the right thing is a terrible reason not to do it). But do something which causes the browser to navigate. fetch is the wrong tool for the job.
I want to change page in server-side.
There is no way to trigger navigation in the browser directly from the server-side. There needs to be something on the client designed to navigate (this might be triggered by client-side code based on data in a response from the server, but it still needs to be client-side).

I'm not sure if I fully undestand your problem, at any rate, take a look at below code, a res.send command sending content to be displayed (https://expressjs.com/en/guide/routing.html).
app.get('/', function (req, res) {
res.send('root')
})
I'd recommend to interest in a template engines
https://expressjs.com/en/advanced/developing-template-engines.html

Fetch is going to do only XMLHttpRequest request to 'lom' (ajax call), which not supposed to redirect your page but to receive just the response in your res parameter.
fetch('/lom').then((res)=>{
console.log(res);
}); //GET Request
So you will see your response in your browser console tab by doing console.log. Anyway if you want to do a redirection do it in the client side, for ex: window.location = '/home'.

Related

After Redirecting to a page after loading another page

Currently I have a page that when you fill out a text box and click a button, it redirects you to another page.
The page needs to be loaded, since it updates and shows xml. (I cannot currently change how this is)
However what I what to do is after page was redirected once, redirect it again or just load another page in general.
The thing to note about the xml link, is that part of it is created with the text box, so it will be dynamic.
I currently have something along the lines of this
//please note that username is a textbox, I've just left it out
<script runat = "server">
void Button_Click(Object sender, EventArgs e)
{
var url = "http://website.com/scripts/" + username.text "/value/0"
try
{
Response.Redirect(url, true);
}
catch(Exception ex)
{//From what I learnt, adding true to redirect throws an exception,
//which is how I tried executing another redirect, but it doesn't seem to
//to load the first direct, and skips straight to this, I also put this
//in finally, because it seemed more appropriate to no avail
Response.Redirect(someurl, true);
}
}
So I'm wondering if this is actually possible, I also wonder if I'm just looking up the wrong keywords to find a solution.
I've spent a bit of time on this, and have yet to come to some sort of solution, but I'm new to web development so I may just be missing some incredibly simple.
Also I only really understand how C# works in asp, but am willing to learn how to add in javascript or VB if necessary.
Thanks in advance for the help
Edit: Solution!
So I managed to use javascript to append the textbox value to the xml link, request it and without showing the user (showing the user, is not necessary in this case).
After which a popup confirms that it is successful then reloads the page.
it is very self explanatory but what I did was
url = "website";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
window.alert("success");
return true;//this reloads the page, that or just window.location.reload();
For an added check, I will see if I can verify that the username is a valid username, and popup with failure text if not.
You seem to have a misunderstanding about what Response.Redirect(...) actually does. The method name is, in my opinion, a bit misleading. It suggests that somehow the Response to the currently executing request will be sent somewhere else than the requesting browser. This is not the case. The name could as well have been Response.SendRedirectResponseToBrowser, because that's what Response.Redirect does.
So when you do Response.Redirect(url) you are telling the server that is executing your page that is should send a response to the browser, telling the browser to do a GET request of the supplied url. The browser will then do that, at which point that page needs to include a separate Redirect in order to further tell the browser where to go next.
In this case then, the page at "http://website.com/scripts/" + username.text "/value/0" needs to be patched up so that after processing the request, it will also send a redirect response with the url you want to display next.
If you have no control over that page, then you must solve this some other way. Some options:
Use ajax to request the "http://website.com/scripts/" + username.text "/value/0" url. Then after completion set the page location to the url you want to show next.
Open the http://website.com/.... url in a _blank target, then set to location to the next page.
Use System.Net.Http.HttpClient in your code behind method to request the http://website.com/.... url, then do a redirect. This means that the server requests the url as part of processing the button click.
Notes:
If the http://website.com/.... url updates some state (like store some changes in a database or similar), then you should request it using a POST request, not a GET. GET requests can get a cached response which means that the server might never actually see the request, and therefore not do any processing.
Piecing together the url like this "http://website.com/scripts/" + username.text "/value/0" looks risky. You should at the very minimum url encode the username.text - HttpUtility.UrlEncode(username.text). Better yet would be the first validate that the entered username is actually a valid user name.
You can add a Refresh header (not a meta-refresh element) to the response that contains the XML. In the header, you can specify another URL and the number of seconds to wait before redirecting.
I guess it should be using JavaScript (front-end) instead of back-end error handling, because it goes to another page. Use promise to handle exception

Refreshing a page with cookies in Play

I have a drop-down selection of available languages. Currently, clicking on a language is mapped to a method in controller which updates the Play Session (which is a cookie under the hood) with the selected language and returns index page.
View:
English
Controller:
def setLanguage(language: String): Action[AnyContent] = Action { implicit request =>
val updatedSession = request.session + (("lang", language))
Redirect(routes.Application.index()).withSession(updatedSession)
}
As you can see, I redirect to index page and it's working fine. However, as the language selection is available at all times on my page, it may be clicked from /resource1, /resource2, /resource3 etc. and I would like to refresh that particular view instead of being returned to home page. I cannot simply get request.uri in the controller and refresh whatever it's pointing to because setLanguage() is mapped to its own route, so my request URI is always /language?lang=whatever.
So, how do I know that prior to invoking GET on /language, client was on, say, /items so I can reload items page instead of returning him to home page? Should I send a GET request with resource as a parameter (e.g. ?lang=en&location=items) to know which page to render? Should I make an ajax request and call window.location.reload() on success? Do I even need to go to server or can I simply update the PLAY_SESSION cookie manually from the client?
I'm using Play 2.3.7.
No you cannot update the PLAY_SESSION cookie from the client side, since it is signed by play with the application secret.
So I think the easiest solution would be, as suggested, to send the current resource as parameter and trigger a redirect.
There is an HTTP header called Referer that contains the url from which the request was made. As far as I know it's supported and used by all modern browsers when you navigate from a page to another.
You can simply redirect to that Referer url.
Another solution is to track in a session or a cookie all pages that are accessed by an user, by using some kind of interceptor in Global.scala or a custom Action builder that you use everywhere. Then in case of language change you can simply redirect to the last page that was accessed by the user.

jquery.post(): how do i honor a redirect from the server?

I'm trying my hand at unobtrusive JS, using JQuery in my Ruby On Rails app.
After the user fills out a form, the client-side JQuery code calls:
$.post("/premises", ui.form)
I can see the POST hit the server, and I can see the server emit a redirect notice to http://localhost:3000/users/42 complete with the data to be displayed.
But the browser page doesn't change. This doesn't really surprise me -- the whole point of client-side javascript is to control what gets updated -- I get that. But in this case, I'd like to honor whatever the server replies with.
I tried extending the call to post() based on How to manage a redirect request after a jQuery Ajax call:
$.post("/premises",
ui.item,
function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
} else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
});
... but (among other problems) data.redirect is undefined. I suspect the real answer is simple, right? Looking forward to it!
The post you refer to uses JSON as return value and it is constructing that json on server side. it means if there is redirect your data object would look like
{redirect:'redirecturl.html'}
and if it is not redirect then data object would be like
{form:html-string-for-form}
now job is to construct json object accordingly on server side
The server is saying that the data you want to process with JavaScript is available at a different URL, not that the browser should load a new document into the top level frame. Sending the browser to the URL where it was told the data it was requesting with JS is wouldn't be honouring the redirect.
If you want to do that, then the server should respond with data (in the body of the response) that the JavaScript interprets as a reason to assign a new value to location.
data.redirect is probably undefined because you're not specifying it on the server side. In the answer you linked to the point was to have the server always respond with 200 regardless of the outcome, and then the JSON body it sends back determines how the client reacts. So, on the server side you'd want to respond with {"redirect" : "/where/to/go"}

changing window.location without triggering refresh

I have an AJAX form that submits GET requests. Because these are all GET requests these should be easily bookmark-able. Preferably I'd make my Ajax request, update the screen and then update window.location.href to be the URL for the new page.
Unfortunately this reloads the page. Is there any way I can get around this? Basically I'd like the URL bar to be a permalink bar, but it needs to be able to change to keep up with the state of the page.
window.location.hash is no good because that doesn't get sent to the server.
window.history.replaceState( {} , title, new_URL );
This will update the current page URL with a new one without refreshing.
Arguments:
Data object (must be one that could be serialized to text)
The new title of the changed window URL
The URL to change to (without refreshing)
The you could use the window.onpopstate = function(event){...} to listen to events when a user goes back or forward in the browser history and change things however you wish.
The hash is the way to go. Because, as you point out, changes to the hash don't get sent to the server, you have to send an async request to the server as well as updating the hash.
As a simple example, if your URL is http://server.com/page?id=4, when the user triggers the action you send an AJAX request for http://server.com/page?id=4, and set the page URL to http://server.com/page#id=4.
Furthermore, you have to have something to restore the state if the user reloads. This would usually be done by reading the hash value client-side and sending an async request to the server based on the state represented by the hash value.
if you want to do which works in current browser, you can't change window.location.href without reloading the page
your only option is to to change window.location.hash.
you can do that each time you make an ajax call. if you're using jquery, you can bind a function which update the hash each time an ajax call is made.
if you choose that you'll have to look for the hash on page load (actually don't know/think you can do that server side) and make that call to have your page on the state corresponding to the hash.
-- update
there is now an API which provide this functionality look for history.pushState, history.replaceState and window.onpopstate : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
it's not availlable everywhere yet ( http://caniuse.com/#feat=history ), there is a few polyfill that you can use for the moment that will use this API if it's available and fall back using the url hash
Consider this JavaScript library: https://github.com/browserstate/history.js
Use jquery. It can do ajax requests. You cant use window.location because that is made to change the url.

Can Response.Redirect and OnBeforeUnload play nice together?

Does anyone know how to detect in a OnBeforeUnload event that the server side code sent a Response.Redirect? I want to prompt a user to keep them from moving away from a page before it's time, but when the server redirects I it shouldn't prompt the user.
I'm working with legacy code that extensively uses Response.Redirect and I'm not interested in changing the way the redirect occurs. Please don't suggest I use X redirect method.
It should be possible to do this based on the response code in the XMLHttpRequest object as a response redirect should send back a 302.
Edit: The Response.Redirect sends back a 200, with a redirect code in the body which then does a window.location.href = new page in the ASP.Net code. Is there any way to get to the server response to determine that this has happened?
I worked out a solution to it.
When the PageRequestManager is processing the response from the server, it will set the _processingRequest flag. In order to allow response.redirect to pass through, I changed my javascript to check for that. The event now looks like this:
window.onbeforeunload = function() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm._processingRequest){
return "Are you sure you want to leave?";
}
};
For non-ajax pages, you're out of luck since the page is never sent to the browser, just the 302 header. So there's no opportunity for javascript processing of OnBeforeUnload.
With ASP.NET AJAX a Response.Redirect really isn't doing a 302. It's sending back a message via the XMLHttpRequest and ASP.NET AJAX is simulating a 302. In theory you could intercept this and perform your own processing...
Yes, Response.Redirect has an overload that lets you decide whether or not to terminate the request (raise a ThreadAbortException). If you let the Response finish (pass false as the second parameter); OnBeforeUnload will also run.
However, simply running OnBeforeUnload will not help you in this case, since your client side code (the prompt) will run before a new page can be sent to the browser (and, if you redirect, it will also only be the 302 header and not the real page).
I would use AJAX to query the server, and if it reports the operation to be completed, allow the redirect in the Javascript code.

Categories

Resources