-1

What I am trying to do is write an endpoint that returns an html and then insert it in another html using Jquery, something like this:

I have a page that have a button, when I click it a ajax request is sent to my controller and I want that controller to render a Twig template and then return it in a html form, then back in my done ajax function, using jquery, insert the html value from that request into a dom element with an specific id.

What I have tried is this

<div class="" id="result"></div>

This is how I send the request

$.ajax({
    method: "POST",
    url: "{{ path('my_controller') }}",
}).done(function (res) {
    console.log("Res", res)
    $("#result").html(res);
}).

And this is my controller code

public function renderAction () {
    $params = [
        "message" => "Lorem ipsum wea"
    ];
    return $this->render('format.html.twig', $params);
}

format.html.twig doesnt have anything special yet, it just prints the message param

It kinda works but my controller sends me back an error twig html that says

Failed to start the session because headers have already been sent by "" at line 0.

That error page is inserted where the #result element is.

What am I doing wrong?

H3lltronik
  • 562
  • 8
  • 26

2 Answers2

1

Try something with this example:

public function renderAction () {
$params = [
    "message" => "Lorem ipsum wea"
];
$view = $this->renderView('format.html.twig', $params);

     return new JsonResponse(array(
                'msg' => 'a msg here if you want',
                'view' => $view,
                'success' => true,
            ));
 }

 // js
 $("#result").html(res.view);
hous
  • 2,577
  • 2
  • 27
  • 66
  • Hi, ty for your answer, it didn't worked, I get the exact same error so I think the problem is no in the response but when rendering the view – H3lltronik May 27 '20 at 22:42
0

This is a little bit embarrassing but I found the problem. When using ajax, if a POST request is being sent you need to add the data field even if its empty, when I changed the request type to "GET" it did worked, when I added an empty data field, it also worked

Thank you so much guys.

$.ajax({
    method: "POST", // Can be GET
    url: "{{ path('my_controller') }}",
    data: {}, // If it is POST this must be with the request
}).done(function (res) {
    console.log("Res", res)
    $("#result").html(res);
})
H3lltronik
  • 562
  • 8
  • 26