samayo
samayo

Reputation: 16495

How to make/handle AJAX requests in Symfony 2

I have a set of sessions in a page, which I want to remove using AJAX. i.e click on a link, and without having to navigate for a new page, just remove the session, and show a message on success.

Someone suggested this approach, but I can't seem to get the sessions removed, neither get a any success/failure messages.

Example controller:

use Symfony\Component\HttpFoundation\JsonResponse;

// ...

public function ajaxRemoveSessionAction()
{
    // Destroy the desired session
    $session = $this->getRequest()->getSession();
    $session->remove('name');

    return new JsonResponse(array('success' => true));
}

Example routing:

ajax_remove_session:
    pattern:  /remove-session
    defaults: { _controller: FooTestBundle:Page:ajaxRemoveSession }

Example twig:

<a href="#" id="remove_session">Remove session</a>

<script type="text/javascript">
$(document).ready(function() {
    $('#remove_session').click(function(){
        event.preventDefault();

        $.ajax({
          url: {{ url('ajax_remove_session') }},
          cache: false,
          success: function(html){
            // do something on success
          }
        });
    });
});
</script>

These are just examples need testing.

Upvotes: 0

Views: 821

Answers (1)

Peter Bailey
Peter Bailey

Reputation: 105878

Did you check your JavaScript console? It doesn't look like you're outputting valid JavaScript

This bit here

$.ajax({
  url: {{ url('ajax_remove_session') }},
  cache: false,
  success: function(html){
    // do something on success
  }
});

Would end up looking like this

$.ajax({
  url: /remove-session,
  cache: false,
  success: function(html){
    // do something on success
  }
});

See the bug? The url is not delimited

You can fix this in one of two ways

  1. Put in the delimiters yourself

    url: "{{ url('ajax_remove_session') }}",
    
  2. Let Twig do it for you

    url: {{ url('ajax_remove_session')|json_encode|raw }},
    

Upvotes: 1

Related Questions