redirection after 'delete' in express - ajax

From the client side, I am making an Ajax request of type "delete" using jquery.On the server side, I am doing res.redirect(URL).But instead of redirecting, browser is again making a delete request with URL returned from server side for redirecting.
However, it is not happening for a post request.Everything is OK with post request.

Short version
Ajax is trying to follow the request to it's bitter end to get a successful response (2xx). If you want to delete a resource and send the user to a new web page, you will need to handle that after receiving a success response from your Ajax call.
Full explanation
While redirects are sometimes used after processing a request (such as a successful / failed login) it's not really what they're intended for. Generally you would only redirect the user to get them to the resource their looking for. For example, you might move an endpoint such as POST /blog-post to the new location of POST /blog-article. What you're saying to the requester here is that something used to be where it is, but now they need to make a request elsewhere to find what they're after. This is incredibly important when trying to prevent link rot.
The idea of accepting and processing a request, and then moving the user off to another page is more of a coincidence really. It just happens to work due to how a browser handles URL requests.
I expect your POST request is actually using a form, in this case the browser is following the redirect because it received something like a 301 and is attempting to see a request chain through. However when using Ajax a redirect is being handled by the Ajax call itself, not the entire browser. Ajax in this case is acting as if you'd expect if the endpoint had been moved. So for example, if you moved the endpoint on the server side, your application would still function as it would follow the redirect instruction.
What you really need to do is return a successful response to your Ajax call such as a 204 (No content) and then in your frontend move the user on to a new page.
This isn't as convenient I'll admit, but when you understand why the redirects actually exist it makes more sense. They're not a way of telling a user to move onto something else, they're a way of trying to prevent link rot and enable applications to continue working against an API which may have changed slightly.

Related

How HTTP redirects(302) works during an ajax call

I was asked to implement a "one session per account" limitation on an old java 7/struts 1 web application.
During development, I'm getting a behavior which I can't really understand.
So if there's an account "Account-A" currently logged in with a session "Session-1234" and then the same account gets logged in but with a different session "Session-4567" then the session "Session-1234" is marked to be invalidated in the next request performed by that session.
During the process of invalidation of the "Session-1234", one of the steps is redirecting(302) the client to the login page.
Now is what I don't understand.
If the request is coming in "synchronous" mode, everything works as expected.
User clicks some link
Server -> invalidates session and redirects(302) login.
Browser -> detects 302 looks for Location header and performs a get.
Server -> serves the resource.
Browser -> show login and update the URL.
If the request is coming in "asynchronous" mode aka AJAX, now I have problems because what happens is that the page never changes and the content of the login is displayed right there.
My question is not how to solve this "problem", but rather have a really good grasp on why it behaves like this.
If you are working with a programmatic client, you have 2 main options:
Don't use cookies, use the Authorization header and let the server emit a 401, telling the client their token is now invalid.
With your javascript client, read if the server returned a 302 response and Location header and respond to that.
#2 is basically a hack that lets you mimic the standard browsers' behavior. #1 is more appropriate for an API.

Getting the page URL where an AJAX call originated from

Many (probably the majority) of AJAX calls are done by a browser on a webpage and that webpage has a URL. Is it possible for a webserver to that's receiving the AJAX request to determine the URL of the webpage where the AJAX call was made? I assume there isn't a standard that requires this data in the headers, but perhaps some browsers include that info? Obviously this doesn't apply if the AJAX call was made from a phone app or other application without a URL.
Very generically (though unreliable), check incoming request headers for Referer. That should give you information about the source page.
Just keep in mind it can be spoofed, absent, etc. and shouldn't be considered bullet-proof (though it doesn't sound like you need it to be anyways).

Redirect AJAX request to another page/View using server Transfer ASP.Net MVC

Is there a way that a MVC Action, initiated by an AJAX request, can redirect the response directly to another page/View without sending a JavaScript “window.location=…” to the client first? In other words, directly transferring the response on the server side and avoiding the roundtrip to the client.
This is a more general question about the possibility to transfer directly an AJAX call, but here is a more specific scenario:
The browser sends an AJAX request to the server and based on the request data the controller's logic performs some operations.
For the majority of the cases, the controller needs to return back a result (JSON) to the same page. However, for few cases it needs to redirect to another page and it returns back a script to redirect the page, but this causes another roundtrip to the browser. The flow is: Page – Server – Page – Server – New Page, and the question is if this can be optimized to Page – Server – New Page .
This isn't really possible, no.
The browser has two options to choose between:
Go to a page
Make an AJAX call to a page
It can't make an AJAX call and automatically redirect based on what the server decides because the client (browser) doesn't know what the server has decided on before the response is even received by the browser.
The traditional approach (which you're avoiding) is:
The browser makes an asynchronous request to the server
The server responds with data informing the client to redirect
The client makes a new request to the server via window.location
The server responds with the new page
However you want to skip a step by doing:
The browser makes an asynchronous request to the server
The client makes a new request to the server via window.location
The server responds with the new page
But the client doesn't know that it needs to redirect and/or it doesn't know how to.
One (ugly) possibility
One idea that comes to mind to pseudo-achieve what you want is to have MVC render the required view and send the whole thing back to the client via JSON rather than a redirection approach. Let me explain.
The browser makes an asynchronous request to the server
The server determines which page needs to be displayed and renders the view (Generating a view without a controller in MVC)
The server serialises the resulting HTML as JSON
The client receives the JSON, and re-renders the entire page with the new markup (i.e. completely replace)
You can also alter the URL and history of the browser to make it "feel" like a redirect by manipulating the browser history.
However I would like to point out that this "solution" is more of an amusing/interesting approach. This isn't really a good way to go about the problem.

Kohana request security

I've searched previous answers but can't seem to find the exact answer.
I am using ajax to call a controller action. This controller action does some other stuff then calls a public function of my user controller:
Request::factory("/user/savepoints/".$new_total);
How can i secure my action_savepoints in the User controller from people just entering it as a URL?
I currently have this at the top of my function but it doesn't do what im looking for.
if( ! $this->request->is_initial() ):
HTTP::redirect('/error');
endif;
Thanks for your help.
Either use an HTTP POST request, which can't be done just by entering a URL. (Though it can spoofed, or done via a form)
Or:
How about generating a kind of token on the server, getting it to the ajax code somehow, then passing it back in the ajax request.
Obviously they could still forge the request manually if they pull the token out of your page, but you issued them the token in the first place.
You could make the token single-use, time limited, or user-specific.
Make sure it contains some kind of checksum with a server secret to prevent people building their own tokens.
Do you want to prevent any unauthorized users to run the script or do you want to make sure that the script only can be run via AJAX calls?
For the first, you can just check if the user is logged in. The AJAX request uses the same session as the ordinary requests.
if (Auth::instance()->logged_in())
For the second you need to check the HTTP headers if it's an AJAX call. But note that this is not a safe way to do it as HTTP headers can be altered by the client and can not be trusteed.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
//This is an ajax call
}
Unfortunately, there's no bullet proof or safe way to detect an AJAX request other than this.

Do I understand Ajax correctly?

I'm been reading up on Ajax and would like to see from the stackoverflow community if I'm understanding everything correctly.
So the normal client server interaction is a user pulls up a web browser types in a url and a HTTP request is sent to the server requesting the page and resources( css, pics ) from the web server. The web server responds to the client via HTTP the page/resources requested and the browser renders the html/JavaScript for the user to view the page.
1) So would it be safe to say that XMLHttpRequest( XHR ) object is doing the same process as the browser except your not requesting html from the server, your requesting text in some type of format?
2) Is it true that a XHR object is much like a regular object that can be manipulated by the program creating the object( like a normal object ), but also sends and receives data with another program( web server ) via HTTP?
3) So in my mind when a XHR is created it is loaded into memory and we setup some of the objects arguments when we do the request.open(“GET”, url, true). Once we do a request.send(null) the object basically attempts to “GET” the url via HTTP and once we get the data back from the server it is put in the responseText argument. Am I understanding this correctly?
4) Also synchronous vs asynchronous. When I think of synchronous I think of steps having to be followed in order. For example, I push a button, data gets sent to server, and I have to wait for data to come back before I can do anything else. With asynchronous connections I would push button, data gets sent to server, I do what ever I want while data gets sent back. Is this a good analogy?
1) Nope. The XMLHttpRequest object does exactly what its name implies -- it initiates an HTTP request. This request can be in XML, or HTML, or PHP. At the end of the day, the browser doesn't care, because in an AJAX request, it doesn't parse the request -- you have to do it yourself. So it doesn't automatically render the HTML from an AJAX request.
2) I'm not sure about manipulation (the XHR object may be immutable) but possibly. Would you ever need to extend it or manipulate it?
Yes, you can change properties of the object and so on. I apologize. I didn't understand you at first :)
3) Yep.
4) That's a great analogy. It's exactly what happens. Another analogy is a 4 lane highway is to asynchronous as a one-way street is to synchronous. If one car breaks down on the 4 lane highway, the rest can keep moving at their normal speed -- but if one breaks down on the one-way road, everything freezes. :)
Here I leave you a good graphic to see clearly the behavior differences between the synchronous and asynchronous application models:
(source: adaptivepath.com)
It would appear that you have a job grasp of how AJAX works. I can't see much to disagree with in your summary of the plumbing of an AJAX application.
I would say however that with the XMLHttpRequest object you aren't restricted to GET. You can also use POST and other HTTP verbs.
With async calls you register a callback function, the XMLHttpRequest object calls your method when the async request completes.
Seems ok to me.
Your first point though is not entirely correct, you can request html from the server using ajax is doesn't have to text, json or xml like most examples show.

Resources