Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.

My Code: //Default Controller

public function indexAction($num, Request $request)
    {
        $request = $this->getRequest();

        if($request->isXmlHttpRequest()){
            $content = $this->forward('PaginationBundle:Default:ajax');
           $res = new Response($content);
            return $res;
        } 

        return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
    }

        public function ajaxAction()
    {
        return $this->render('PaginationBundle:Default:page.html.twig');
    }
}

My Js: When clicking on #target, I'd like to load page.html.twig in my div

$("div#target").click(function(event){
    t = t +1;
    $.ajax({
       type: "POST",
       cache: "false",
       dataType: "html",
       success: function(){
       $("div#box").append(data);    
       }
    });
  });

I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig

Thanks everybody in advance

like image 670
rpa Avatar asked May 19 '26 00:05

rpa


2 Answers

In your $("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success' parameter of ajax call.

$("div#target").click(function(event){
    t = t +1;
    $.ajax({

       type: "POST",
       url: "{{path('yourpath-means header name in routing.yml')}}",
       cache: "false",
       dataType: "html",
       success: function(result){
       $("div#box").append(result);    
       }
    });
  });

Hope this helps... Happy coding

like image 94
Asish AP Avatar answered May 20 '26 12:05

Asish AP


This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.

The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:

success: function(data){
    $("div#box").append(data);    
}
like image 26
Sgoettschkes Avatar answered May 20 '26 14:05

Sgoettschkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!