JSF 1.2 AJAX Redirect to URL - javascript

I've got a requirement where we need to redirect to a page for JSF 1.2 Ajax call. In our case, we need to redirect to session expired page when the ajax call get fired after the session got expired. We are implementing the session expiry check in a filter and the invocation of httpservletresponse.sendRedirect is redirecting correctly to the session expired page as expected, but the url is not getting changed which is the issue now.
Any hints/soultion either at the client/server side is highly appreciated.
~Ragesh

Finally I managed to find a solution for the above problem.
In the filter, I set the response header "Location" and another custom header which I'll use in the client side to filter the response.
Filter code:
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setHeader("x-timeout-status", "true");
httpServletResponse.setHeader("Location", httpServletResponse
.encodeRedirectURL(sessionexpiryurl));
Richfaces have got a javascript file with various callbacks required during the AJAX call invocation which is packed inside the Richfaces libraries. There is one callback function called "processResponse" which will get invoked upon receiving response for all AJAX call initiated by JSF Ajax components . I've made use of this to handle the redirection functionality.
JS code:
var originalAjaxProcessResponse = A4J.AJAX.processResponse;
A4J.AJAX.processResponse = function(req) {
if (req.getResponseHeader('x-timeout-Status') != undefined && req.getResponseHeader('x-timeout-status') == 'true') {
window.location.href = req.getResponseHeader('Location');
} else {
originalAjaxProcessResponse(req);
}
}
Here we are overriding the method to handle our specific case and delegate the rest of the ajax call response handling to the in-built processing provided by richfaces.
Please let me know if you see any limitation to this solution or have a better solution to this problem
~Ragesh

Related

Why can NodeJS request set post form later using Chain API?

I am try to figure out why we can set the form for the post request using .form after I have called request.post.
This is the code snippet from official document
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}},
function(err,httpResponse,body){ /* ... */ })
I am confused about the second example request.post('http://service.com/upload').form({key:'value'}).
In my opinion, it should not work because once request.post(...) has been called, the request will be sent. And then the call to .form is like you are setting the post form after the request has been sent. So how can this work ? Is there anything wrong ?
And then the call to .form is like you are setting the post form after the request has been sent. So how can this work ?
Apparently, when you do this:
request.post('http://service.com/upload')
The request is not immediately sent. Instead, it is registered (with a setImmediate() or process.nextTick()) to be sent on the next tick of the event loop.
So, when you execute request(...).form({key:'value'}), the .form() gets a chance to modify the request before it is sent.
In the doc for .post(), there is this statement that explains:
For advanced cases, you can access the form-data object itself via r.form(). This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling form() will clear the currently set form data for that request.)
In that above statement, r is the return value from calling request.post() so r.form() refers to request.post(...).form(...) which is your specific situation.
And, in the source code is this comment:
// start() is called once we are ready to send the outgoing HTTP request.
// this is usually called on the first write(), end() or on nextTick()

How do I intercept an API call and display data from it using a UserScript?

There's a webapp that makes a request (let's call it /api/item). This request returns a json body with a field called itemData which is normally hidden from the user, but I want to make that shown.
So how do I make a userscript that listens for the request at /api/item and displays the itemData field?
For reference the way the webapp is making the request is:
return Promise.resolve(new Request(e,r)).then(sendCookies).then(addLangParam).then(addCacheParam).then(addXsrfKey).then(checkZeroRating).then(function(e) {
return fetch(e)
}).then(checkStatus).then(checkApiVersionMismatch).then(checkApiResponse)
Most of that is irrelevant, but the important part is Request (I think).
This webapp is not using XMLHttpRequest, but the Fetch API.
You can use the fetch-intercept npm module to intercept fetch requests. Example code:
import fetchIntercept from 'fetch-intercept'
fetchIntercept.register({
response(response) {
console.log(response)
return response
}
})
Do you have access to the promise returned ?
If so, then you may add another "then".
Otherwise, you may overwrite "checkApiResponse"

jQuery submit preventDefault

I load a page from example.com on port 80, then from the loaded page, submit a form to the same server on a different port (as defined in the form action attribute).
(html)
<form id="enabledForm" action="http://example.com:39991/updateEnabled" method="POST">
(javascript)
$('#enabledForm').submit()
This works fine and the data is delivered as expected to the form action url, but the browser is redirected to the address of the POST request instead of staying on the requesting page.
If I use
$('#enabledForm').submit(function (event) {
event.preventDefault();
});
or
$('#enabledForm').submit(function (event) {
return false;
});
then the server receives no data but the page is not redirected.
if I add an alert within the event handler then the alert is not shown.
$('#enabledForm').submit(function (event) {
alert('inside submit event handler');
return false;
});
Clearly I'm soing something wrong but after hours of headbanging and trying everything I can think of I'm stuck.
What to do?
You have two basic options here:
Have the server return a 204 No Content response and forget about using JS entirely
Prevent the submission of the form with JS and send the data to the URL with Ajax instead
No content:
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent.
How you set the HTTP response status code depends on your server side language / framework. For example:
In Catalyst it would be something like:
$c->response->status(204);
In PHP it would be:
http_response_code(204);
There are many Ajax tutorials out there, so I'm not going to provide another one. The jQuery documentation has a detailed section on Ajax.
Note that since you are working across origins (different ports), you will need to circumvent the Same Origin Policy. The standard way to do that is with CORS.
Sending a form would automatically change your browser URL (and refresh view).You should use an Ajax request to send informations to your server and eventually retrieve completion (success, error, informations...).
Extract your inputs' values to an object via Jquery and send your request via Jquery.post or Jquery.get
$('#enabledForm').submit(function (event) {
//Prevent natual post
event.preventDefault();
//Retrieve inputs values
var data = {}
$('#enabledForm input,textarea').each(function(index){
data[$(this).attr('name')] = $(this).val();
});
//Send request
$.post('http://example.com:3999/updateEnabled',data,function(response){
//Parse response if you want to inform user about success of operation
});
});
I don't know if val() is usable with all of yout inputs, but it's easy to adapt...

I need to know about the response type of $.ajax() method in jquery

I am working on an e-commerce site and I need google sign-on it, so when a user creates his/her shopping list and click on the add to list button. I am able to send my data through the $.ajax() method, so what I exactly want is when the response from ajax method come it should redirect me to Login page if the user is not logged in, else it should save my object.
In the target endpoint of that .ajax() call, check your authentication, and if the user is not logged in, set the response header to - 401 Unauthorized.
Then in the .ajax() do this:
$.ajax(function() {
//.. your other ajax stuff..//
error: function(jqXHR, textStatus, errorThrown) {
// only redirect if user unauthorized - 'errorThrown' has text part of HTTP status header
if(errorThrown == "Unauthorized") {
window.location.href = "myloginpage.html";
}
}
});
The response header being set to 401 will trigger .ajax()'s error function, instead of the success function.
Edit:
Changed the error function to only redirect on Unauthorized
Also note, that if this is a cross-domain jsonp call, it won't work, as jsonp requests fail silently and don't trigger the error function
check in your response callback function and write your programming logic that you want
$.ajax({
'url':location,
'type':type,
'success':function(response){
/*write here your logic*/
},
'error':function(){
/*you code for error handling*/
}
});
to redirect window by javascript use
window.location.href = 'your location';
You can redirect to login page using window.location = 'yourlocation' in either success or error function of the response (depending upon what response you are gettig from server. If you are bringing the response code in header 401 error function will be executed other wise success).
but i think what you would like to have is take user back to the same page after login from which he started.
If you are interrested in this, you can use spring security for this. Its very easy to integrate if you are using spring already.
If you are not using spring you might look for some alternative for the same. Following links may help you
Spring Security Ajax login
http://java.dzone.com/articles/implementing-ajax
In jquery there is .post() method found to do this. In action page you can do whatever you want.

Intercept send mail AJAX request in Gmail

I'm trying to attach a callback to the "Send mail" ajax action in Gmail. I've been able to differentiate a Send mail action from other AJAX actions based on the request payload but have been unable to hook into the actual AJAX call.
Thus far, I've tried using overriding the XMLHttpRequest.open() method as detailed here. That hasn't worked. I've also tried overriding XMLHttpRequest.send(). Also failed.
Any thoughts? Much thanks in advance.
Google's trick is that they send the request from inside an iframe which has it's own JavaScript environment. However, since it is loaded from the same origin as the parent, you can still easily manipulate it even from the browser console:
[].slice.apply(document.querySelectorAll('iframe')).forEach(function (iframe) {
try {
var xhrProto = iframe.contentWindow.XMLHttpRequest.prototype;
var origOpen = xhrProto.open;
xhrProto.open = function () {
console.log('DO SOMETHING', arguments);
return origOpen.apply(this, arguments);
};
} catch (e) {}
});
You might want to use a MutationObserver to detect newly added iframes reliably.

Categories