How to save an ajax response in firefox - javascript

I need to find a way to write ajax responses to a file. The responses are XML strings, which is more than fine by me.
What I would like to do, is click on something in my webpage, and save the XML that is returned to a file.
But since I know, that Javascript can't access local files by itself, it is also possible to just send the data on to another server, where PHP would take care of this.
Now the place where I'm stuck is the javascript and the interception. I know, that some of this can be done using greaseMonkey in Firefox. If so, how? Thanks!
Edit: Some explaining.
The script that creates the output is not written by me.
Yes, I could see the data in Firebug, seeing is one thing. I need to interpret the data
There are a lot of requests going on here. About 1 every 2 seconds, so copying them by hand isn't an option.
Still, help?

You should provide more details, a link to the target page is best.
Is the page using jQuery?, Some other library?, or custom XMLHttpRequest() calls?
Anyway, a simpler approach may work, try it first...
If the AJAX data is being written to the page, attach a DOMSubtreeModified event listener to the container element. Something like:
document.getElementById ("ContainerID").addEventListener ("DOMSubtreeModified", YourFunction, false);
function YourFunction () {
//--- Get the target node's inner HTML and send it to our server.
}
Note that DOMSubtreeModified events work fine in FF and Chrome, the two main browsers for Greasemonkey.
If the data is not being written to the page, then the best way to intercept the AJAX depends on if the target page is using a library like jQuery.
A generic way to intercept AJAX can be seen in this SO question (and others).
As you said, once you have the data, to automatically write it to a file, use GM_xmlhttpRequest() to send it to a server that you control.

Why cannot you do it like this?
Save AJAX response to file on the server side and then provide a link to it, so it can be downloaded.

Firebug will also help, you can view in very convenient way each response in few formats, and eventually copy/save it.

Use a normal (non-AJAX) request and add a Content-Disposition: attachment; filename="foo.xml" header to the response.

If you're just going to save the XML, why are you using AJAX? Just set location.href to the location of a PHP script that sends a "Content-disposition: attachment" header and gives the XML in the response body. AJAX seems totally the wrong tool for the job.

Related

Using JavaScript to send String to Servlet, and Results from servlet back to JavaScript

First of all: sorry for my bad grammer. English isn't my native language, but i will try to exlpain my problem as simple as i can.
I'm working on a web-application, where user can enter a link. (Question 1) This link should be send to the server/servlet and will be progressed to other things. (Question 2) After the progression, the servlet will send a json-array (?) back to the javascript-part of my app.
I'm completly new to this kind of stuff, but its very important to me, to find out how this works or better, how i can make this work. Its actually very simple, but i used plenty of weeks and cant figure it out.
The application is using the SAP UI5-libs (Question 3), where i would also like to know, if there is any possible way, to parse JSON with the UI5 libs.
I hope, i could explain my problem good enough, so i can get some help. Thanks to all!
The 'sending' of the string to the server/servlet would happen via ajax in either POST or GET form. That is up to you.
I recommend you use a javascript plugin like jQuery (JQuery Ajax API) because the regular ajax code is a bit messy.
As for the servlet/server communicating back to the client is as simple as writing to the page. In a typical servlet context it would be something like
out.print("This is a message");
where Ajax automatically returns the content of the entire page upon callback.
So in conclusion:
Consider test.jsp your servlet. I wish to send "Hi" from the client (being the browser) via GET to the servlet and I want the servlet to say "Hello" back.
I would open an ajax request of type GET to the url "test.jsp?param=Hi". In the servlet I receive this page request and process it. The servlet discards the parameter because it is not used and outputs "Hello" to the page.
In the client the ajax will have returned "Hello" and I can use this to put it into a var or whatever and all of this happened while not refreshing and not navigating in the original document where I did the javascript.
Another way is using websockets where you basically use sockets in javascript to send and receive any kind of data.
Also please check out this possible duplicate question: How to send a string to a servlet from javascript using xmlhttprequest

Is it possible to use inject $.post() from address bar?

I have a javascript in which I use $.post() command to post variables to a php file, I have the URL of the php file hardcoded in the same .js file.
I just want to know if it's possible for someone to inject $.post() command from address bar and send invalid data to the PHP file?
if yes, how to prevent or how to detect those invalid data?
Yes, anybody who knows how to code in JavaScript could send an AJAX POST request to your PHP file.
As for how to detect the invalid data, that depends entirely on what makes the data invalid. You'll simply need to check the POST values against whatever criteria you're expecting valid data to meet, and then ignore any requests that don't meet those criteria.
Yes, it's very simple. Attacker can modify, add or remove any JavaScript running in the browser, modify DOM, etc. Tools like Firebug allow anyone to call arbitrary JavaScript from the console. Moreover one can simply use curl to run your server and send arbitrary data.
if yes, how to prevent or how to detect those invalid data?
You must ensure data validity and integrity on the server side. Also you might want to add some security on the server side and do not depend on some JavaScript function being "hidden".
Sure, by prepending the script with the javascript: scheme you can do pretty much anything you want to a site:
javascript:$.post(/* stuff here */)
You should always validate your incoming data on the server side, because not only may someone use the javascript on your site to do this, but they may use other tools, like curl or whatever else that will let you make http requests.

Use JSONP to load an html page

I'm trying to load an external page using JSONP, but the page is an HTML page, I just want to grab the contents of it using ajax.
EDIT: The reason why I'm doing this is because I want to pass all the user information ex: headers, ip, agent, when loading the page rather than my servers.
Is this doable? Right now, I can get the page, but jsonp attempts to parse the json, returning an error: Uncaught SyntaxError: Unexpected token <
Sample code:
$.post('http://example.com',function(data){
$('.results').html(data);
},'jsonp');
I've set up a jsfiddle for people to test with:
http://jsfiddle.net/8A63A/1/
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Making a JSONP call (in other words, to employ this usage pattern),
requires a script element. Therefore, for each new JSONP request, the
browser must add (or reuse) a new element—in other words,
inject the element—into the HTML DOM, with the desired value for the
"src" attribute. This element is then evaluated, the src URL is
retrieved, and the response JSON is evaluated.
Now look at your error:
Uncaught SyntaxError: Unexpected token <
< is the first character of any html tag, probably this is the start of <DOCTYPE, in this case, which is, of course, invalid JavaScript.
And NO, you can't use JSONP for fetching html data.
I have done what you want but in my case I have control of the server side code that returns the HTML.
So, what I did was wrapped the HTML code in one of the Json properties of the returned object and used it at client side, something like:
callback({"page": "<html>...</html>"})
The Syntax error you are facing it's because the library you're using expects json but the response is HTML, just that.
I've got three words for you: Same Origin Policy
Unless the remote URL actually supports proper JSONP requests, you won't be able to do what you're trying to. And that's a good thing.
Edit: You could of course try to proxy the request through your server …
If you really just want to employ the client to snag an HTML file, I suggest using flyJSONP - which uses YQL.. or use jankyPOST which uses some sweet techniques:
jankyPOST creates a hidden iframe and stuffs it with a form (iframe[0].contentWindow.document.body.form.name).
Then it uses HTML5 (watch legacy browsers!) webMessaging API to post to the other iframe and sets iframe's form elements' vals to what u specified.
Submits form to remote server...done.
Or you could just use PHP curl, parse it, echo it, so on.
IDK if what exactly ur using it for but I hope this helps.
ALSO...
I'm pretty sure you can JSONP anything that is an output from server code. I did this with ClientLogin by just JSONPing their keyGen page and successfully consoleLogged the text even though it was b/w tags. I had some other errors on that but point is that I scraped that output.
Currently, I'm trying to do what you are so I'll post back if successful.
I don't think this is possible. JSONP requires that the response is rendered properly.
If you want another solution, what about loading the url in an iframe and trying to talk through the iframe. I'm not 100% positive it will work, but it's worth a shot.
First, call the AJAX URL manually and see of the resulting HTML makes sense.
Second, you need to close your DIV in your fiddle example.

With JS, jQuery, how do I save an AJAX response to a (text) file?

It seems like this question is asked periodically and the common response is "You shouldn't do that with AJAX anyway. Just set the window location to the file."
But I'm trying to request a file that doesn't actually exist out on the server anywhere. It's dynamically generated (by a Django view) given the GET/POST context parameters. The file I want to retrieve via AJAX, and then save to the client machine, is a text file (csv).
I can currently get the text to the client machine (and can verify this by seeing it in logging or an alert) but cannot then figure out how to save this text to a file inside of the AJAX success callback fn.
Essentially, is this possible, is it something JS can do? That is, to open file save dialogs for "files" that are actually AJAX response text?
From the browser's point of view, it doesn't matter if the file exists or not, it's just a resource on a server that it's requesting. I think you're going to need to do some version of "Just set the window location to the file". If you set the content type in the header to something that the browser doesn't recognize, I believe it will ask the user if they want to save it.
As others mentioned, you can't do it only with JavaScript.
IMO the best option would be the Flash 10+ FileReference API.
There are some good JavaScript wrapper libraries like Downloadify that provide a JavaScript API to access those methods.
Give a look to this demo.
This isn't something JavaScript (and therefore jQuery or anything other JS framework) is allowed to do, for security reasons. You may be able to do what you want to flash or another route, but not JavaScript. Bear in mind Flash has it's own slew of security restrictions for this as well.
(Yes, IE can do this via an ActiveX object, but I'm not counting that as a "solution" here)
Basically, no. Javascript cant save anything to the local machine due to security restrictions. Your best bet may be to have a signed applet that the user can trust to write the file, or put it in a textarea that they can then easily copy and paste into a new file.
Could you not use the PHP rename() function for this, instead of just Javascript? Call to a PHP file and pass the name of the file you want to copy along with where as parameters?
I have the same problem. You can try this
<button id="Save">Save</button>
<img src="MakeThumbnail.ashx?Image=1.jpg" id="imgCrop">
$("#Save").click(function (e) {
url = $("#imgCrop").attr("src")+"&Action=Save"
e.preventDefault(); //stop the browser from following
window.location.href = url;
});

Asynchronous cross-domain POST request via JavaScript?

I could just create a form and use that to do a POST request to any site, thing is the FORM method isn't asynchronous, I need to know when the page has finished loading. I tried messing around with this using an iframe with a form inside, but no success.
Any ideas?
EDIT
unfortunately I have no control over the response data, it varies from XML, json to simple text.
You can capture the onload event of an iframe. Target your form to the iframe and listen for the onload. You will not be able to access the contents of the iframe though, just the event.
Try something like this:
<iframe id='RS' name='RS' src='about:blank' onload='loaded()'></iframe>
<form action='wherever.php' target='RS' method='POST'>...</form>
script block:
var loadComplete = 0
function loaded() {
//avoid first onload
if(loadComplete==0) {
loadComplete=1
return()
}
alert("form has loaded")
}
IF you want to make cross domain requests you should either made a JSON call or use a serverside proxy. A serverside proxy is easy to set up, not sure why people avoid it so much. Set up rules in it so people can not use the proxy to request other things.
If the data returned from the cross domain post is JSON, then you can dynamically add a script tag pointing to the URI that returns the data. The browser will load that "script" which then you can access from other javascript.
YUI3's IO object offers cross-domain requests, however it does so using a small Flash control it embeds on the page.
While there is work going into secure cross-domain requests from JavaScript, at this time, you need to use a plugin like Flash or Silverlight as a bridge with which to make the request.
You can't do anything cross-domain using javascript. You'd have to use a backend language like PHP or asp or something.

Categories