0

I have an action to set a Travel enabled , it works good but now I'd like to make it with ajax so I have installed FOSJsRoutingBundle but the problem is that I don't know how to write the ajax code.

Route

travel_enable:
path:     /travel/enable/{id}
defaults: { _controller: "AppBundle:Travel:enable" }
options:
    expose: true

Action

    public function enableAction(Travel $travel)
    {

    $em = $this->getDoctrine()->getManager();

    $travel->setEnabled(true);

    $em->flush();

    $referer = $this->getRequest()->headers->get('referer');
    return $this->redirect($referer);
}

twig

<a href="{{ path('travel_enable', {'id': entity.id} ) }}" class="btn btn-xs btn-success" title="Enable"> Enable </a>

javascript

<script type="javascript">
    // what to put here else

    Routing.generate('travel_enable', { id: '...' });

</script>

1 Answer 1

1

Is there a any other reason behind using FOSJsRoutingBundle than because of ajax capability?

If no, you could remove it and pre-generate all URLs needed. Something like this

Twig:

<a href="{{ path('travel_enable', {'id': entity.id} ) }}" class="btn btn-xs btn-success dyn-link" title="Enable"> Enable </a>

JS:

$('a.dyn-link').on('click', function(){
    var URL = $(this).attr('href');

    $.post(URL, {
        // Your post data here, if any
    }).done(function(response){
        alert("Suceess!");
    }).error(function(){
        alert("Error!");
    });
});

Now, the diffrent approach is needed when you dynamically generate your <a> tags, in which case you will need FOSJsRoutingBundle:

Twig:

<a data-entity-id="YOUR-ENTITY-ID-GOES-HERE" class="btn btn-xs btn-success dyn-link" title="Enable"> Enable </a>

JS:

// You have to use event delegate
$(body).on('click', 'a.dyn-link', function(){
    var entityId = $(this).attr('data-entity-id');

    var URL = Routing.generate('travel_enable', { id: entityId });

    $.post(URL, {
        // Your post data here, if any
    }).done(function(response){
        alert("Suceess!");
    }).error(function(){
        alert("Error!");
    });
});

Hope this helps...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.