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

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: