Zul Huky
Zul Huky

Reputation: 333

Ajax with twig, how it works?

From my controller I send several parameters in my html.twig, then I want to make a AJAX request like this one :

{% if text is defined %}
    var text = {{ text }};
    var sender = {{ sender }};
    var date_send = {{ date_send|date('d/m/Y') }};
    var mess_type = {{ mess_type }};
    var to = {{ to }};

    $.post('send.php', {text:text, sender:sender, date_send:date_send, mess_type:mess_type, to:to}, function(data)
    {
        $('#Map').text(data);
    });
{% endif %}

SO when I do that, I have this error :

POST http://localhost:8000/send.php 500 (Internal Server Error)

My send.php is where my html.twig is. I just have an echo "hi" in my send.php for testing, but it does not display anything.

I also tried to put a send function in my controller :

/**
* @Route("/send.php", name="send")
*/
public function send(Request $request) {
    dump("hi");
    echo "send";
    return null;
}

And I replace 'send.php' by {{path('send.php')}} inside my html.twig (inside $.post()). I know I can't return null, but It does not display my dump. And I have this error :

An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "/send" as such route does not exist.")

And it does not get me to /send.php. I don't know what can I miss, I didn't find any solution on google. Thank for your help.

Upvotes: 0

Views: 1166

Answers (1)

Matteo
Matteo

Reputation: 39390

A controller's method should return a Response object so try this:

/**
 * @Route("/send.php", name="send")
 */
public function send(Request $request)
{
    return new Response('send');
}

The twig path function need the route name instead of the path, so try the following:

{{path('send')}}

Hope this help

NB: I order to identify the real error message, try put the url in the browser and see what happen

Upvotes: 2

Related Questions