Post an Ajax form with jquery

This snippet shows how to post a form to an Ajax url and insert the results into a div.


<form data-xhr-uri="/api/post" data-xhr-target-selector="#results">
(...)
</form>

<div id="results">
</div>
<script>
        $('form[data-xhr-uri]').on('submit', function (e) {
            e.preventDefault();
            try {
                var $form = $(this);
                $.ajax(
                    {
                        type: 'POST',
                        url: $form.data('xhr-uri'),
                        data: $form.serialize(),
                        success: function (data) {
                            $($form.data('xhr-target-selector')).html(data);
                        }
                    }
                );
            } catch (e) {
                console.log(e);
            }

        });
</script>