I am trying to create a web API that allows someone (well, preferably a program) to submit a large binary file and receive an ID for that file in return. I have some HTML with a form (method="POST") and an <input type="file" ...> element that can submit a file to some PHP code, using the standard multipart/form-data MIME type. The PHP generates the ID and prints it out as its result. Because the PHP simply prints the ID, as opposed to redirecting to another HTML page or generating HTML itself, it is not very pretty, but hopefully is sufficient for the intended use case of a programmatic file submit API.
So far, so good. It gets tricky when I want to have client-side code capture the returned ID and invoke other APIs with it. If the client is a web page with JavaScript, it seems like the client should use XMLHttpRequest, but it is not clear to me how to get that object to use the file the user selected with the file input control.
I would love for the same API to work both with manually operated web forms (for easy UI and testing), and purely programmatic invocation (like with JavaScript, curl/libcurl, etc.). I don’t want the PHP to issue a redirect to another page with the ID in the query string, and I don’t want to return HTML directly. I just want a simple file in, ID out API.
Since this is proving difficult I suspect I am going about things the wrong way. I am open to alternative designs, but I would prefer to keep things as simple as possible. I found a somewhat similar question, but it is too Java-centric and doesn’t quite address my problem.
I had to do something similar, and what I ended up doing was submitting the form to a hidden iframe. The response from the php can then simply be retrieved in an iframe onload handler.
In fact, here is the code I used:
Note:
submitdestinationis my iframe.cvdetailsis my form. The target for the form was set tosubmitdestination. Also, I am using Mootools, in case any one noticed the missing hash in my dollar arguments.Here is a stripped down version of the HTML I used (although the iframe is unchanged):
The save button had a click handler that could be reduced to: