5 ms·
> If you dont want to use ajax to send your form submission, another solution would be to just repopulate the form fields with the stored data, then calling for
by cagmz 9y ago
> If you dont want to use ajax to send your form submission, another solution would be to just repopulate the form fields with the stored data, then calling form.submit()
What are the pros and cons between these 2 approaches?
- jbob2000 9y agoIt mostly depends on the server receiving the form submission. If your server is setup to receive form posts, constructing a form post in javascript would be really cumbersome, so just repopulating the form and resubmitting would be the easiest. But if your server handles JSON, you can just take your stored data and post it right to the server.
- wongarsu 9y agoUsing jquery, the following looks exactly like the submitted form to the server side: $.ajax({ type: "POST", url: url, data: $("#form").serialize(), // serializes the form's elements. success: function(data) { //do stuff } }); Instead of serializing the form, jquery can also just serialize a flat js object. I wouldn't call that complicated enough to make a distinction. (it's probably really easy in modern plain js too)
- jbob2000 9y agoIn your example, you'll also need to change the headers because $.ajax will set content type to application/json, which wouldn't work if your server is setup to receive x-www-form-urlencoded or multipart/form-data. Starting to get complicated now, might be easier to just do $("#form").submit().
- wongarsu 9y agoright, forgot to change the header. Sure, it's more complicated than $("#form").submit(). But it's close enough that other considerations become more important (e.g. do I want a page reload, do I have to populate the form first etc)
- dsego 9y agoWill that work for file uploads?
- collyw 9y agoTried something like that in Django, but needed another page of JS to get CSRF tokens to work. Its not always as simple as the first suggestion.
- hobarrera 9y agoYeah, but the returned data is completely different. On one case, you'd expect a new page which the browser would render. In the other, a response which is handled via JS.