2

I would like to use AJAX in my Symfony3.0.3 project. The communication works, but I can't get variable from JS to the handler. In the direction handler to JS, it works fine.

I'm trying to get the variable from the request with "$request->query->get('id'))" but I only get "null".

In an other way I'm trying to use the variable from the URL but I get this error:

"An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("id") to generate a URL for route "admin_ajax".") in CommonBundle:Default:index.html.twig at line 421."

I don't mind using a solution or an other (I'll use the best one depending of your advices), but I still would like the solution for both error.

JS

function selectClient(idClient)//idClient = 1
{
    alert(idClient);
    $.post('{{path('admin_ajax')}}',{idClient: id}, 
            function(response)
            {
                if(response.code == 100 && response.success)
                {
                    alert(response.id);//Show null if using $request->query->get('id')) in handler but should be 1
                }}, "json");    
}

routing:

admin_ajax:
    defaults: { _controller: CommonBundle:Default:getClient }
    path:     /ajax/{id}

handler:

public function getClientAction($id)
{
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $isAjax = $request->isXMLHttpRequest();
    if ($isAjax)
    {
        $response = array("code" => 100, "success" => true, "id" => $request->query->get('id'));
        return new Response(json_encode($response));
    }
    $response = array("code" => 0, "success" => false);
    return new Response(json_encode($response));
}

EDIT: Thank for Rim, and Rvanlaak answer, I used the FOSJsRoutingBundle.

JS

function selectClient(idClient)
{
    $.get(Routing.generate('ajax_getclient', { id:idClient }), 
            function(response)
            {
                if(response.code == 100 && response.success)
                {
                    alert(response.id);
                }
                else
            }, "json");
}

routing:

ajax_getclient:
    defaults: { _controller: CommonBundle:Default:getClient }
    path:     /ajax/{id}
    options:
        expose: true

Note that the option "expose: true" was necessary to works.

1 Answer 1

1

Thats because the twig is executing before javascript so he is not reconizing the client id param

i had the same problem and resolve it using FOSJSRoutingBundle see this post :

Ajax url parametetr using Twig path

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.