Get jQuery post redirect response - javascript

I've written some HTML/Javascript that sits on a third-party server for security reasons. This page performs a javascript post to another page on the same site. However, instead of responding with useful data, it instead wants to perform a redirect (if you would post via a normal HTML form to this page, it would redirect your browser). How can I process this process? I basically want to be able to extract the url's query parameters that it is trying to redirect with (and then put this link into a hidden form field).
Here is my basic ajax post...
$.ajax({
url: '/someurl/idontcontrol',
data: serialized_form_data,
async: false,
type: 'POST',
success: function(data, textStatus, x) {
alert(x);
alert(x.getAllResponseHeaders());
return false;
$('#redirect_link').val(WHAT_DO_I_PUT_HERE);
}
});
Note that the URL I am posting to is not one that I control, so I have no power over what it returns.
UPDATE: When I use the above alerts, I receive "[object XMLHttpRequest]" and "null". I'm monitoring the headers with a Firefox plugin and they seem be coming back as expected, but I can't seem to access them via javascript (I've also tried x.getResponseHeader('Location'), but that and all other calls to getResponseHeader return empty).
ALSO: I don't know if it matters, but the status code is 302 (as opposed to 301 or 303).
Thanks!

According to the jQuery Documentation the success method can take a third argument which is the XMLHttpRequest object.
According to Mozilla's XMLHttpRequest page, this object should have a "status" property. If you check the value of this property, and it is a redirect code, such as 301 (permanent redirect) or 303 (temporary redirect) it is known the processing page is trying to perform a redirect. The "statusText" property should be able to be used to determine the location it is trying to redirect you to.
If you know it is trying to redirect, you can then re-post the data through Ajax to the new URL.
The strange thing is though, when researching this, stumbled across this page that indicates the XMLHttpRequest object should follow redirects (see the comments). So it seems like this would be a non-issue.
Unless the processing page is using an HTML meta redirect (like below) to do the redirection. In that case, I'm not sure what could be done - maybe try to parse the returned HTML for meta tags and see if any of them are attempting a redirect.
<meta http-equiv="refresh" content="0;url=http://www.example.com/some-redirected-page">

You can't get the full HTTP headers from an AJAX call in JQUery, so you can't process the redirect in this way.
However with a raw javascript request you do have access to the XMLHttpRequest getAllResponseHeaders() method which will allow you to process the redirect (this function for single headers).

Sorry, not directly an answer to your question, but I'm sure it's possible with jQuery too as it's quite simple with Prototype.
// Warning: this is Prototype, not jQuery ;-)
//...
onComplete: function(response) {
var refresh = response.getResponseHeader("Refresh");
var whatever = response.getResponseHeader("Whatever");
}
//...

Related

How to send a request from JavaScript without base URL?

I'd like to send a request to a simple URL from my JavaScript, so that the base URL will NOT be added to the request URL. For example, the request should be sent to the following URL (without the base URL):
SAPEVENT:SOME_TEXT?2
I used the jQuery's $.ajax function in order to implement it, but without success.
Here is a JSFiddle for it:
http://jsfiddle.net/txb6tdjj/2/
The JS code:
function sendEvent(id) {
$.ajax("SAPEVENT:SOME_TEXT?" + id);
}
sendEvent(2);
I see the following error in the JS console:
XMLHttpRequest cannot load sapevent:SOME_TEXT?2. Cross origin requests
are only supported for HTTP. (jquery-2.1.0.js:8556)
I even set the parameter crossDomain: true, but it didn't help:
http://jsfiddle.net/auhx2v2v/3/
The JS code:
function sendEvent(id) {
$.ajax({
url: "SAPEVENT:SOME_TEXT?" + id,
crossDomain: true
});
}
sendEvent(2);
It ends up with the same error.
It works correct in the HTML like this:
http://jsfiddle.net/1f6npcn2/2/
The HTML code which works correctly:
<FORM action="SAPEVENT:PRESS_ME">
Click on me to send an event!
<INPUT TYPE="submit" VALUE="Press me to send an event!"/>
</FORM>
But I need to implement it in JavaScript, so that a request parameter can be set dynamically in the URL in JavaScript.
Do you know how to implement it in JS so that the request will be sent to the URL SAPEVENT:SOME_TEXT?2 without the base URL?
Additional information about used browsers: The error is shown only in Chrome. IE and Firefox do not show an error, but they also don't send the request.
Additional information for the SAP guys: I know there is a SAP Note 191908 which states that it's impossible, but a colleague has confirmed that he has successfully tested such functionality in an HTML page which used the same code as I copied above (see the HTML code above and http://jsfiddle.net/1f6npcn2/2/). So the SAP Note is wrong. I know how I can implement this functionality in HTML, but I don't know how I can implement it in JS. That's the problem.
I have no experience of working with SAP but I think you are missing a crucial part here.
In the samples you gave SAPEVENT:CLICK_ON_ME isn't a http url at all but rather it would invoke whatever handles the SAPEVENT-protocol on the local computer with the parameter CLICK_ON_ME. I'm guessing that you have some sort of client installed on your computer that does this for you (how do I create my own URL protocol? (e.g. so://...) contains some more information on how this is accomplished).
The reason your error-message talks about crossdomain-stuff is probably because it tried to interpret it as host:port.
So in other words, since this isn't a http url there isn't a webserver working on the other end so you can't do ajax-requests against it.
The SAPEVENT: stuff is not handled by any web server. The SAP GUI uses an embedded Internet Explorer and registers a custom protocol handler. There is no use in trying to use ajax techniques since you need to reach the container of the client, not the server. To reiterate: You do not want to "send a request" anywhere, you want to convince the browser that a certain local navigation event happened". SAP Note 191908 contains more information on that topic.
No idea about SAP Views, but to me this seems like a usual behaviour on webservers. I presume that SAPEVENT gets parsed by the server during the runtime to a more regular URI. Only the views get parsed, not the resources like CSS and JS, so the SAPEVENT placeholders in the JS file don't get parsed and the JS interpreter will not accept it as a valid URI. One of the common ways of solving this, is to create either a hidden form in the HTML or just a hidden input containing the server-generated values you are needing. For example
SAP View:
<input type="hidden" id="my_event_url" value="SAPEVENT:PRESS_ME">
JS:
function sendEvent(id) {
$.ajax({
url: $('#my_event_url').val() + '?' + id,
crossDomain: true
});
}
sendEvent(2);
I finally implemented it in JavaScript. Thanks go to this web page.
I modified the solution which was shown in this web page in order to add a link instead of a form in JavaScript.
This is the working solution in JS:
var targetUrl = "SAPEVENT:SOME_TEXT?2";
function sendSapEvent(targetUrl) {
var link = document.createElement("a");
link.setAttribute("style", "display:none;");
link.setAttribute("href", targetUrl);
// Move the click function to another variable
// so that it doesn't get overwritten.
link._click_function_ = link.click;
document.body.appendChild(link);
link._click_function_();
}
sendSapEvent(targetUrl);
You can find it also in this JSFiddle: http://jsfiddle.net/708r95p0/6/
It works! It sends a request to the URL sapevent:SOME_TEXT?2
I decided to use a link instead of a form element, bacause I couldn't pass the request parameter using a form.

JSONP request callback

Ok, after an whole day trying to get this to work I just don't seem to know what's the deal with this, so here it goes:
I have a WebService hosted locally by now (http://localhost:15021/Service1.svc/[whatever_method]) and an HTML Page on a different file.
FYI, both WebService and HTML Page will get hosted on different servers.
I'm trying to get some info off the WebService to the HTML Page by the onload=load() method in the HTML Page.
My JavaScript code is:
function load() {
alert("Loading...");
$.ajax({
url: 'http://localhost:15021/Service1.svc/getAllNoticias',
type:'GET',
dataType: 'jsonp',
jsonp: 'loadNews_callBack'
});
}
function loadNews_callBack(result){
alert(result.data);
}
Additionally, the JSONP is loaded on the Page with an OK (200) status (As you can see here) which should (I guess) call the callback function, but it isn't.
What can I do to get around this? I already change the request parameters 500 times (e.g., added "?callback=? to the url, with or without jsonp attribute, etc...)
Any help would be great,
Thanks in Advance
Check the actual response text to verify that the response is correctly being wrapped by the callback function. It is possible that your service is not setup correctly to handle JSONP so it simply responding with JSON. It will still come back as 200, but fail to execute.
loadNews_callBack([json...])
vs
[json...]
See this question as reference on how to go about updating your service:
ASP.net MVC returning JSONP

read content from Twitter sample using Javascript

I'm pretty new to programming, and recently have been playing with Twitter API. From statuses/sample method, how would you read the content of following URL using Javascript?
https://stream.twitter.com/1/statuses/sample.json
Edit: perhaps I shall explain my intention. I'm trying to read the Twitter sample data, read the hashtags every 30 seconds, and then sort them ascendingly every 30 seconds the top 10 hashtags.
The problem is, I'm not even sure how to read the Twitter data in the first place..
Not looking for solutions, but definitely could use some ideas.. especially for getting started.
You should be able to utilize JSONP which is a special type of response back from the server.
It basically takes the response, wraps it in an anonymous function callback, and returns it to the client inside of a script tag thereby calling it when the response gets back to the browser.
​$.ajax({
type: 'post',
dataType: 'jsonp',
url: 'http://twitter.com/status/user_timeline/msdn.json?count=10&callback=?',
success: function (data) {
console.log(data);
}
});​
Inspecting the request url in Chrome's debugger you'll see the request...
https://twitter.com/status/user_timeline/msdn.json?count=10&callback=jQuery1706531336647458375_1335842234009&_=1335842234045
And the response back is...
jQuery1706531336647458375_1335842234009( /* data */ );
Then jQuery wraps the data in the script tag and appends it to the body.
Notice how the callback in the request matches the function call in the response.
Hope that helps!
You can't. Read up on cross site scripting.
Basically you're going to need to proxy your request through the hosting server.

Any way to identify a redirect when using jQuery's $.ajax() or $.getScript() methods?

Within my company's online application, we've set up a JSONP-based API that returns some data that is used by a bookmarklet I'm developing. Here is a quick test page I set up that hits the API URL using jQuery's $.ajax() method:
http://troy.onespot.com/static/3915/index.html
If you look at the requests using Firebug's "Net" tab (or the like), you'll see that what's happening is that the URL is requested successfully, but since our app redirects any unauthorized users to a login page, the login page is also requested by the browser and seemingly interpreted as JavaScript. This inevitably causes an exception since the login page is HTML, not JavaScript.
Basically, I'm looking for any sort of hook to determine when the request results in a redirect - some way to determine if the URL resolved to a JSONP response (which will execute a method I've predefined in the bookmarklet script) or if it resulted in a redirect. I tried wrapping the $.ajax() method in a try {} catch(e) {} block, but that doesn't trap the exception, I'm assuming because the requests were successful, just not the parsing of the login page as JavaScript. Is there anywhere I could use a try {} catch(e) {} block, or any property of $.ajax() that might allow me to hone in on the exception or otherwise determine that I've been redirected?
I actually doubt this is possible, since $.getScript() (or the equivalent setup of $.ajax()) just loads a script dynamically, and can't inspect the response headers since it's cross-domain and not truly AJAX:
http://api.jquery.com/jQuery.getScript/
My alternative would be to just fire off the $.ajax() for a period of time until I either get the JSONP callback or don't, and in the latter case, assume the user is not logged in and prompt them to do so. I don't like that method, though, since it would result in a lot of unnecessary requests to the app server, and would also pile up the JavaScript exceptions in the meantime.
Thanks for any suggestions!
When using the AJAX methods within jQuery, it should be setting a header of 'X-Requested-By: XMLHttpRequest' in the request.
My initial thinking would be that you could check and see if that header is set on the server side, and if so, instead of issuing a redirect, send back some JSON with a redirection URL, and have the client JS look for the presence of that redirection in the response, with the server only issuing the redirect when it's not an AJAXy call.
According to the jQuery documentation if you don't specify dataType as script, as you are doing now, it'll try to figure out what the response is based on the MIME type. You could then also add an option called dataFilter to the $.ajax method; it is a function which takes two parameters, dataFilter(data, type) and type is the data type as determined by jQuery, you can look at the type and procede accordingly.

detecting JSON loaded by browser

I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:
{"authentication":"required"}
The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.
However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:
Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!
The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.
If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.
Cheers,
Don
3) Change your AJAX code to add a variable to the GET or POST: outputJson=1
You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.
There are two options that I can see:
Add a parameter to the page by appending a URL parameter to the screen that modifies the output.
URL: http://domain/page.jsp?ajaxRequest=true
would output json only
URL: http://domain/page.jsp
would display a jsp page that could forward to another page.
OR
change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.
4) Read up on the 'Accept' request HTTP header.
Then, on the server side tailor the output:
e.g.
if(Accept contains application/json...) { // client asking for json, likely to be XHR
return {"foo":"bar"}
} else { // other
return "Location: /login-please";
}
Start with a smarter error message, like this:
{"error":"authentication required"}
Wrap the JSON output in a callback:
errorHandler({"error":"authentication required"});
Have a handler waiting in your script:
function errorHandler(r) {
alert(r.error);
}
And don't forget to send it down as text/javascript and not application/x-json.

Categories