Submit a post request with ajax for PHP

1

I'm trying to send text that is typed via ajax to a php page that will make a query using that text that is received. I want to know how to send the value of nmCliente to the php page. I tried the following code and the return was 500 (Internal Server Error) . I'm using the framework Symfony

Follow the codes.

Jquery

                var nmCliente = $("#nome").val();

                $.ajax({
                    url: "../buscacliente",
                    type: "POST",
                    data: nmCliente,
                    dataType: "text"

                }).done(function(resposta) {
                    console.log(resposta);

                }).fail(function(jqXHR, textStatus ) {
                    console.log("Request failed: " + textStatus);

                }).always(function() {
                    console.log("completou");
                });

PHP

/**
 * @Route("/buscacliente", name="busca_cliente")
 * @Method({"GET", "POST"})
 */

public function buscaContratoAction(Request $resquest)
{
    if ($request->isXMLHttpRequest()) {
        return new JsonResponse(array('data' => 'this is a json response'));
    }

    return new Response('This is not ajax!', 400);
}
    
asked by anonymous 16.05.2018 / 16:16

1 answer

0

Dude, you need to use the FosJsRouting bundle in your symfony application. It is highly recommended, and there is no secret to using the library! When you have everything installed and working, you will use it in the parameter within the options={"expose"=true} annotation, according to the following example:

/**
 * @Route("/foo/{id}/bar", options={"expose"=true}, name="my_route_to_expose")
 */
  public function indexAction($foo) {
   // ...
  }

And in javascript you will call the route through the function Routing.generate() .

          var url = Routing.generate('my_route_to_expose', { id: 10 });
            $.ajax({
                url: url,
                type: "POST",
                data: nmCliente,
                dataType: "text"

            }).done(function(resposta) {
                console.log(resposta);

            }).fail(function(jqXHR, textStatus ) {
                console.log("Request failed: " + textStatus);

            }).always(function() {
                console.log("completou");
            });

It will work cool! Hugs!

    
24.07.2018 / 16:38