bench-o
bench-o

Reputation: 2339

Symfony2 and AJAX

Im wondering how to do asynchronous actions in Symfony2 without reloading the page. I dont find anything about on the "Book" and the "Cookbook". (Only thing I found was 2 sentences about hinclude.js?)

Im thinking of: Sending a form without reloading the page(save into db), reload parts of the page, etc.

Upvotes: 1

Views: 414

Answers (1)

Rooneyl
Rooneyl

Reputation: 7902

A rough template for a controller function.
It includes a check if ajax and just returns JsonResponse.

public function ajaxAction(Request $request)
{
    if (! $request->isXmlHttpRequest()) {
        throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
    }

    // do whatever
    $rtn = array('foo' => 'bar');

    return new \Symfony\Component\HttpFoundation\JsonResponse($rtn);
}

Standard ajax code to put in view;

<div id="my-foo">bob</div>
<script type="text/javascript">
var jqxhr = $.ajax({
                url: '{{ path('route_to_controller_function') }}', // path should be in your routes.php
                type: 'post',
                data: {param1: 'foo'}, // if required
            })
            .done(function(data) {
                // do whatever you want
                // for example write foo to div
                $('#my-foo').html(data.foo);
            })
            .fail(function() {
                alert( "error" );
            });
</script>

Upvotes: 1

Related Questions