3 ms·
Using jquery, the following looks exactly like the submitted form to the server side: $.ajax({ type: "POST", url: url, dat
by wongarsu 9y ago
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)
- 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.