Using the google App Engine, I am looking to implement javascript (or Ajax) for POSTing a form and updating the target div. The form includes multiple fields and files for transfer. The javascript function I am using is extracted from the "Javascript: The Definite Guide" book. I have two specific inquiries:
- How should I structure the "data" argument in the postFormData() function within "form.html" to pass all fields and files correctly?
- Is there a recommended way to design the callback function so that the response from "form.html" can update the content div?
Appreciate any assistance with this.
base.html:
...
<div id="content">
{% include "form.html" %}
</div>
Image:<br />
<img src="/file?entity_id={{entity.key}}" />
<br />
<script type="text/javascript">
function postFormData(url, data, callback) {
if (typeof FormData === "undefined")
throw new Error("FormData is not implemented");
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if (request.readystate === 4 && callback)
callback(request);
};
var formdata = new FormData();
for (var name in data) {
if (!data.hasOwnProperty(name)) continue;
var value = data[name];
if (typeof value === "function") continue;
formdata.append(name, value);
}
request.send(formdata);
}
</script>
...
form.html
<form action="/form" method="POST" enctype="multipart/form-data">
name1: <input type="text" name="name" />{{ name1 }}<br /><br />
name2: <input type="text" name="name" />{{ name }}<br /><br />
...
file1: <input type="file" name="file" />{{ file1 }}<br /><br />
file2: <input type="file" name="file" />{{ file2 }}<br /><br />
...
<input type="submit" value="Submit" onclick="return postFormData('/form', howToPrepareData?, whatIsTheCallbackFunction?)" />
</form>