Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 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?



It 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.


Using 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)


In 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().


right, 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)


Yeah, 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.


Tried 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.


Will that work for file uploads?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: