Intercepting XHRs - javascript

Is it possible to intercept when the browser does a XHR?
Regardless of JavaScript libraries used?
Like
setTimeout(function() {
// jQuery XHT
$('#container').load('foo.html');
}, 5000);
When the jQuery.load fires, I want to intercept this and add an url parameter to the request.
Thanks in advance for tips and info.
Best regards
tan

Not possible for all frameworks no, you'll have to do it on a per framework basis as they all build them differently. If this was only to be used by your own code then there is nothing stopping you writting a wrapper for you XHR calls which could tag the additional data on the end.
What is it you are wanting to send? A cache breaker? Tracking? Also why for all frameworks?
Also if you want to just debug the requests you can use Firebug in Firefox to see all XHR requests that get sent.

Well each JQuery ajax methods return an XHR (except for load), so you could set your own onreadystatechange if you wanted to.

Yes you can - http://github.com/jpillora/xhook - implements a wrapper over XMLHttpRequest2 allowing you to change view and modify a request before it is made and after it is returned

Related

Post/Get handler in Jquery/Javascript

I am doing a web application,
which creates a lot of post & get requests.
I can see all the requests using Develop Tools in Mozilla/Chrome, and also in Charles (application).
Is it possible to create a jquery/javascript function which will listen for all requests on current page, and will alert each request to me?
Something similiar to Jquery .click() function.
example:
$('body').post(function() {
alert(this.Url + this.Parameters);
});
I googled, and couldn't find, hope there is a way.
Yes,in Jquery you have Global Ajax Event Handlers
These methods register handlers to be called when certain events, such
as initialization or completion, take place for any Ajax request on
the page
refer the Documentation

How to intercept ajax calls to return mock data.

In my previous angularjs project I used interceptors to intercept the http calls, and to be able to serve mock data instead of the real data from the server. I found it very useful throughout the development process.
My question is, how could I do this without angularjs (In my current project I use another framework, which does not have interceptors)?
Is there any other http library out there, that supports this? How could I achive this using jquery's or superagent's http capabilities?
So i found the following script: https://github.com/creotiv/AJAX-calls-intercepter/blob/master/index.html
Here is a live fiddle: http://jsfiddle.net/0eyadb88/1/
I'm not going to go over everything in the script as simply it looks like it does handle the XMLHttpRequest as i commented on. To what extent this works, well that would be just some testing of course and should be able to be expanded.
i've added a non jquery ajax call (testing with chrome here) and it handles that as well.
The main section to pay attention to is
(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
alert('Intercept');
open.call(this, method, url + ".ua", async, user, pass);
};
})(XMLHttpRequest.prototype.open);
Personally i would use this approach unless a decent libary is around, but of course if such a libary exists. please do let us know ;)
Otherwise cleaning up the script or using that one in general should be fairly easy.
You should check out dfournier/plasticine. I developed this library in order to intercept a request and fake the response or intercept server response and modify it. I use it at work and the backend team is not ready but we already defined the API.

Internet explorer intercepts XML response

I have a form whose target is an iframe.
When submitting the form, the response is XML and I have Javascript that analyzes the response.
I noticed that when running on IE, IE intercepts the response and treats it as an RSS feed, so my code never receives the response. If I disable the RSS feeds (from the internet option, content tab) everything works ok.
I set the content type of the response to “text/xml; charset=UTF-8” but still it does not work.
Is there any workaround?
The best workaround would be not to use an iframe in this case. It sounds like IE is catching the http response and reading it on its own. Is there a reason you're not making an AJAX call to retrieve the information? It sounds like you're relying on JavaScript to handle the response anyway, so I would think that using an XMLHttpRequest object would be better for you: http://www.w3.org/TR/XMLHttpRequest/
If that's too complicated, look into a library like jQuery: http://jquery.com/ that has built in (and much simpler) functions to make AJAX calls and handle responses.
To expand on this, you would bind the submit function of the form to a JS function (or use jQuery to do it) and pick up the form data, send it in an AJAX request, and handle the response. jQuery has a built in function serialize() which is meant to convert form data on a page into information ready for use in the ajax() function to send to the server. If you're unfamiliar with the XMLHttpRequest object, I would highly suggest using a library like jQuery for this task.
OK, found the problem…
My response XML contains FEEDBACK tags.
IE treat these tags as RSS feeds. Changing the tag name to FDBACK resolve this issue…
MS, why this is not documented???
Yes, also make sure the file is output with the correct Content-Disposition using headers, do that IE gets "response.xml" and not "response.php" or some such...
'Content-Disposition: attachment; filename="response.xml"'

Enabling back/fwd key events for an Ajax Application

I have an application which works heavily on AJAX. However I want to have navigation functionalities in it. To spoof the url, I am changing the location.hash, to generate URL. But if I use back/fwd, only the url changes, but page wont reload. How can I override the hstory.back to reload the page.
I don't know of any other way than continuous polling to implement this behaviour. An implementation might look like this:
var lastHash = '';
function pollHash() {
if(lastHash !== location.hash) {
lastHash = location.hash;
// hash has changed, so do stuff:
alert(lastHash);
}
}
setInterval(pollHash, 100);
You can't exactly capture the back event, but most of these problems have been solved - and a good thing too, it's a hard problem.
Take a look at really simple history (aka RSH) and either implement it or work through it to see how it works.
The answer for this question will be more or less the same as my answers for these questions:
How to show Ajax requests in URL?
How does Gmail handle back/forward in rich JavaScript?
In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:
jQuery History (using hashes to manage your pages state and bind to changes to update your page).
jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).
The balupton answers are really great.
But you also have another jQuery Plugin to handle your ajax requests, it is address.

Cross domain Ajax request from within js file

Here's the problem:
1.) We have page here... www.blah.com/mypage.html
2.) That page requests a js file www.foo.com like this...
<script type="text/javascript" src="http://www.foo.com/jsfile.js" />
3.) "jsfile.js" uses Prototype to make an Ajax request back to www.foo.com.
4.) The ajax request calls www.foo.com/blah.html. The callback function gets the html response and throws it into a div.
This doesn't seem to work though, I guess it is XSS. Is that correct?
If so, how can I solve this problem? Is there any other way to get my html from www.foo.com to www.blah.com on the client without using an iframe?
It is XSS and it is forbidden. You should really not do things that way.
If you really need to, make your AJAX code call the local code (PHP, ASP, whatever) on blah.com and make it behave like client and fetch whatever you need from foo.com and return that back to the client. If you use PHP, you can do this with fopen('www.foo.com/blah.html', 'r') and then reading the contents as if it was a regular file.
Of course, allow_remote_url_fopen (or whatever it is called exactly) needs to be enabled in your php.ini.
There is a w3c proposal for allowing sites to specify other sites which are allowed to make cross site queries to them. (Wikipedia might want to allow all request for articles, say, but google mail wouldn't want to allow requests - since this might allow any website open when you are logged into google mail to read your mail).
This might be available at some point in the future.
As mentioned above JSONP is a way around this. However, the site that you are requesting the data from needs to support JSONP in order for you to use on the client. (JSONP essentially injects a script tag into the page, and provides a callback function that should be called with the results)
If the site you are making a request to does not support JSONP you will have to proxy the request on your server. As mentioned above you can do this on your own server or what I have done in the past is use a http://www.jsonpit.com, which will proxy the request for you.
One option is to implement a proxy page which takes the needed url as a parameter. e.g. http://blah.com/proxy?uri=http://foo.com/actualRequest
JSONP was partially designed to get around the problem you are having
http://ajaxian.com/archives/jsonp-json-with-padding
JQuery has it in their $.getJSON method
http://docs.jquery.com/Ajax/jQuery.getJSON
The method shown above could become a large security hole.
Suggest you verify the site name against a white list and build the actual URI being proxied on the server side.
For cross domain hits this is a good working example and now is considered as some what "standard" http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html.
there are other ways as well, for eg injecting iframes with document.domain altered
http://fettig.net/weblog/2005/11/28/how-to-make-xmlhttprequest-connections-to-another-server-in-your-domain/
I still agre that the easy way is calling a proxy in same domain but then it's not truly client side WS call.

Categories

Resources