Download file via POST in one request with JavaScript - javascript

Sometimes when making an HTTP request to download a file (e.g. PDF, XLSX, etc.) from the own webserver, it is necessary to use the HTTP method POST, because it requires dynamic input data. I have been trying different ways to reduce that to one single HTTP request for best performance, but could not succeed.
As JavaScript with the XMLHttpRequest object (AJAX) can not "download" files, I guess it requires an HTML workaround. The only working solution I found for that case is generating a form element wrapping input elements containing the data. I could not find a way how to send boolean values via this, as AJAX is able to. That would mean: it is not suitable for a standardizable implementation.
My question is: How can I download a file via one POST request which can include boolean values (JavaScript)?
In case it is important: The backend system I use is Ruby on Rails

As #Pointy mentioned, boolean values are always translated to strings in HTTP communication. I was wrong about that in my question. That means, converting a JavaScript JSON string or a classic object to an HTML form (then submitting and deleting it) works!
Actually sending an AJAX request and then manually triggering a link click to the generated file has the advantage of being able to use a progressbar.

Related

ContactForm 7 and javascript to capture form data

I have a WordPress site and i use a cf7 form to make a booking enquiry. When the form is submitted an email is send to my info#.. and also a custom php file i made is passing data from the form to a CRM platform.
I use JS on_mail_sent action and i capture all the values of the form and im passing it to the php file via query (.php?id=id&......).
I want to ask if this method is acceptable or i must use another method. For example is there any way certain browsers for some reasons dont support javascript?
Thank you.
The better solution to use POST method to submit form.
About difference between Get and Post:
GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
HTTP/1.1 specification (RFC 2616) section 9 Method Definitions contains more information on GET and POST as well as the other HTTP methods.
One more important moment:
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.
All popular browsers supports Javascript.
Regards.

Passing large amounts of data from one page to another without POST?

I'm using a web server framework which works with only GET requests, at the moment I'm trying to pass a large amount of data, that is the text content in a textarea which comes from user input, into another page which echoes the user's input.
I've attempted Querystrings but I end up receiving the error "Requested URL too long".
Any suggestions as to what method I should use?
If you can only send data encoded in GET requests, then you will have to break up the request and send it in multiple parts.
You could either use Ajax or store the entire set of data in localStorage and fetch each chunk in turn as the page reloads.
One approach would be to make a request to an end point that allocates you a unique ID. Then send a series of requests in the form: ?id=XXX&page=1&data=... before closing it with ?id=XXX&total_pages=27 at which point you assemble the different pieces on the server.
This way lies madness. It would be much better to add POST support to your framework.
Try using Javascript Cookies.
you can store the textarea value there and then read it in another page (or wherever you want).
Here's a tutorial
http://www.w3schools.com/js/js_cookies.asp

Upload a string as file using form post in javascript

I want to fake a file upload without using a file input. The file's content is generated from a string. i.e. I want to post some string to a server with content-type "multipart/form-data".
But the server is with different domain and doesn't support CORS, therefore I could not use XMLHttpRequest. Is it possible to do this using only normal form post?
That is actually a nice question. In my humble opinion, what you are looking for is not possible for various reasons as listed below:
You can surely have an HTML form something like this:
<form ....>
<input id="blah" type="input" name="nameblah" ..>
...
</form>
But as you would know, you really cant access/modify the "contents" of the file selected. Immediate solution will be to use a hidden field as an alternative and set the enctype=multipart/form-data, but for hidden field the browser will not set proper Content-Disposition Headers.
You could have an AJAX call in which you manually build up the entire request body, but that would be a cross domain call, as you have already noted. The usual bypassing techniques apply.
Solution would be to let the server, which serves out the HTML, fulfill the skydrive request for you. In that case you would be uploading the file using HTML form, or javascript. The file will then be "forwarded" to the skydrive server.
In case you are trying via Javascript, be sure to get the multipart/form-data format correctly. Here is the RFC

Simple HTML POST without any server scripting, can be done using JS

I want to pass some textbox value strictly using POST from one html page to another...
how can this be done without using any server side language like asp.net or php
can it be done using javascript??
thnx
You can't read POST data in any way on javascript so this is not doable.
Here you can find similar questions:
http://forums.devshed.com/javascript-development-115/read-post-data-in-javascript-1172.html
http://www.sitepoint.com/forums/showthread.php?454963-Getting-GET-or-POST-variables-using-JavaScript
This reading can also be interesting: http://en.wikipedia.org/wiki/POST_%28HTTP%29
This expecially suggests why this answer (wikipedia is the source):
GET
Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.
(This is also true of some other HTTP methods.)[1] The W3C has
published guidance principles on this distinction, saying, "Web
application design should be informed by the above principles, but
also by the relevant limitations."[10] See safe methods below.
POST
Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request.
This may result in the creation of a new resource or the updates of
existing resources or both.
POST data is added to the request. When you do a GET request the data is added to the url, and that's why you can access it through javascript (and that's why it's not parsed and you have to do it manually). Instead, POST send data directly into the http requests, which is not seen in any way by the html page (which is just a part of what is sent through the http request).
That said, only server side language will receive the full HTTP request, and definitely you can' access it by javascript.
I'm sorry but that is the real answer

Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests?

How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?
On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser.
if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)
So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.
Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.
I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.
So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?
Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.
Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.
My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static GET and POST handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment.
Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.
When dealing with AJAX, I use this:
from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.
I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out uni-form. Pinax has a good implementation of this in their voting app.
FYI, this isn't an answer...but it might help you think about it a different way
Here's the problem I'm running into...Google App Engine + jQuery Ajax = 405 Method Not Allowed.
So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(.

Categories