Skip to content

Instantly share code, notes, and snippets.

@elucas
Last active December 14, 2015 08:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elucas/5056751 to your computer and use it in GitHub Desktop.
Save elucas/5056751 to your computer and use it in GitHub Desktop.
This is the Ajax form submission -> content update code that reaffirmed my Man-Crush on Ben.

When you submit the form#filters_form, it requests the response in the background, replaces the existing contents of #article_blocks with the #article_blocks from the response, and updates the url with the params given.

Oh, and if it fails, it redirects you to the form url, so that you're not left in a broken ajax state.

So:

  • No fancy ajax logic server-side
  • No fancy ajax logic client-side
  • Just the bit of content you wanted gets updated

Disclaimer: Tweaks would be needed for POST forms

$.fn.submitMatch = function(other){
return this.on('submit',function(e){
e.preventDefault();
var form = $(this);
var url = form.prop('action') + '?' + form.serialize();
$.get(url)
.pipe( $ )
.then(function($doc){
$(other).replaceWith($doc.find(other));
if(window.history && window.history.replaceState){
history.replaceState({},document.title,url);
}
})
.fail(function(){
document.location = url;
});
});
};
$('#filters_form').submitMatch('#article_blocks');
@rjmunro
Copy link

rjmunro commented Feb 28, 2013

That looks like a strange use of .pipe(). Why not just do $doc = $(doc) in the .then() function?

You can pass the fail function as the second parameter of .then(), rather than chaining it. This is more Promises/A like, which is what jQuery's .then() is based on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment