Mick
Mick

Reputation: 31919

Reload a specific controller after Ajax Call

I have embed a controller in a template:

{% render "AcmeUserBundle:User:showUsersList"} %}

<a onClick="changeStatus({{user.getUserId()}})"

The aim is simple:

At the moment, I managed to do this, by reloading the entire page using document.location.reload(true); This has no point so far...

Here is the ajax part:

//...
function changeStatus(userId){
    $.ajax({
        type: "POST",
        url: ajaxControllerPath,
        data: "userId="+userId,
        success: function(){
            document.location.reload(true); 
        }
    });  
}

How would you reload the embedded controller only?

Upvotes: 1

Views: 4424

Answers (2)

Mick
Mick

Reputation: 31919

This is working so far:

Embed the controller within a div:

<div id="block1">
    <a onClick="changeStatus({{user.getUserId()}})"
</div>

And reload the controller using javascript at the end of the ajax call

$('#block1').load("{{ path('show_users_list') }}");

Does anyone have a better suggestion?

Upvotes: 3

Carlos Granados
Carlos Granados

Reputation: 11351

When you call the ajax controller, this controller could render the showUsersList template and return the generated html as a json object:

$answer['html'] = $this->forward('AcmeUserBundle:User:showUsersList')->getContent(); 
$response = new Response();                                                
$response->headers->set('Content-type', 'application/json; charset=utf-8');
$response->setContent(json_encode($answer));
return $response

Then in your javascript use this generated html to replace the content of the controller part of the page (use a div or similar to identify it)

<div id="changethis">{% render "AcmeUserBundle:User:showUsersList"} %}</div>

function changeStatus(userId){
    $.ajax({
        type: "POST",
        url: ajaxControllerPath,
        data: "userId="+userId,
        success: function(returnData){
            $('#changethis').html(returnData['html']);
        }
    });  
}

Upvotes: 2

Related Questions