简体   繁体   中英

Can't pass parameters using AJAX + Symfony 4

I'm using AJAX to request client names from my DB using autocomplete() inside an input #descricao . It requests a route that I created inside Symfony 4 (/acao). The problem is that I'm trying to set a parameter (/acao?parametro= clientname ) but I'm get an error:

Could not resolve argument $parametro of "App\\Controller\\DefaultController::filter()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

I tried to change my routes.yaml:

acao:
  path: /acao
  controller: App\Controller\DefaultController::filter
  methods: GET

but it didn't work.

script.js:

$( "#descricao" ).autocomplete({
        source: function( parametro, response ) {
                $.ajax({
                    url: '/acao',
                    dataType: "json",
                    data: {
                        parametro: $('#descricao').val()
                    },
                    success: function(data) {
                        response(data);
                    }
                });
        }
    });

DefaultController:

/**
     * @param string $parametro
     * @return JsonResponse
     * @Route("/acao", name="acao", methods="GET")
     */
    public function filter(string $parametro){

        $em = $this->getDoctrine()->getManager()->getRepository(Clients::class)
            ->createQueryBuilder('c')
            ->andWhere('c.name_fantasy ilike :parametro')
            ->setParameter('parametro','%'.$parametro.'%')
            ->getQuery()
            ->getArrayResult();

        return new JsonResponse($em);
    }

What am I doing wrong?

ANSWER:

I managed to make it work using POST and changing table name c.name_fantasy to values :

Controller:

/**
     * @param Request $request
     * @return JsonResponse
     * @Route("/acao", name="acao", methods="POST")
     */
    public function filter(Request $request){
        $q = strtoupper(trim($request->request->get('parametro')));

        $em = $this->getDoctrine()->getManager()->getRepository(Clients::class)
            ->createQueryBuilder('c')->select('c.name_fantasy AS value')
            ->andWhere('c.name_fantasy like :parametro')
            ->setParameter('parametro', '%'.$q.'%')
            ->getQuery()
            ->getArrayResult();

        return new JsonResponse($em);
    }

AJAX:

$( "#descricao" ).autocomplete({
        source: function( parametro, response ) {
                $.ajax({
                    url: '/acao',
                    dataType: 'json',
                    method: 'POST',
                    data: {
                        parametro: $('#descricao').val()
                    },
                    success: function(data) {
                        if (data.length > 0) {
                            response(data);
                        }
                        else {
                            data = '';
                            response(data)
                        }
                    },

                });
        }
    });

Firstly, you dont need use routes.yaml for routing, if you use the Route Component:

Symfony\\Component\\Routing\\Annotation\\Route

So just delete that stuff from routes.yaml.

EDITED:

/**
 * @param Request $request
 * @return JsonResponse
 * @Route("/acao", name="acao", methods="GET", options={"expose"=true})
 */
public function filter(Request $request)
{
    //you should strip and trim the parameter, like (just basic):
    $clientName = strip_tags(
        trim($request->query->get('parametro'))
    );

    // ...
}

Where Request is Symfony\\Component\\HttpFoundation\\Request <-- you need add to the use statements!

If this not working for you, with your original ajax (what in your question), try on this way:

    // ...
    let formData = new FormData();
    formData.append("parametro", $('#descricao').val());

    $.ajax({
        url: '/acao',
        // ...
        data : formData,
        // ...

JUST A TIP:

I recommend, use the symfony/bundles/FOSJsRoutingBundle . You can link your routes in js like this:

import Routing from '../../vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router';
import Routes from '../../public/assets/js/fos_js_routes.json';

Routing.setRoutingData(Routes);

// ...
    $.ajax({
        //acao is your route name and you route in this case:
        url: Routing.generate("acao"),

Dump the latest added routes, with this command:

php bin/console fos:js-routing:dump --format=json --target=public/assets/js/fos_js_routes.json

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM