简体   繁体   中英

Single Ajax in symfony2

i have to integrate ajax in my proyect, something like the seeker of google . i did something like this:

pedido.html.twig

/**... html code...
...
...
...**/

$(document).ready(function(){

            var consulta;


            $("#busqueda").focus();


            $("#busqueda").keyup(function(e){

                  //obtenemos el texto introducido en el campo de búsqueda
                  consulta = $("#busqueda").val();

                  //hace la búsqueda

                  $.ajax({
                        type: "POST",
                        url: "{{ path('buscar_productos') }}",
                        data: "b="+consulta,
                        dataType: "html",
                        error: function(){
                              alert("Error petición ajax");
                        },
                        success: function(data){                                                    
                              $("#busqueda").empty();
                              $("#busqueda").append(data);

                        }
                  });


            });

    });

PD: "#busqueda" is my input.

TablasController.php

public function buscarProductos(){
        $em = $this->getDoctrine()->getManager();
        $productos = $em->getRepository('ProyectoAdminBundle:Catalogo')->findAll;

        return $this->render('AtajoBundle:Ajax:buscarProductos.html.twig', array('productos' => $productos));
    }

buscarProductos.html.twig

<?php

      $buscar = $_POST['b'];

      if(!empty($buscar)) {
            buscar($buscar);
      }

      function buscar($b) {
            $con = mysql_connect('localhost','root', 'root');
            mysql_select_db('base_de_datos', $con);

            $sql = mysql_query("SELECT * FROM anuncios WHERE nombre LIKE '%".$b."%'",$con);

            $contar = mysql_num_rows($sql);

            if($contar == 0){
                  echo "No se han encontrado resultados para '<b>".$b."</b>'.";
            }else{
                  while($row=mysql_fetch_array($sql)){
                        $nombre = $row['nombre'];
                        $id = $row['id'];

                        echo $id." - ".$nombre."<br /><br />";    
                  }
            }
      }

?>

My real problem is that when I call AJAX, this is going to look for the information to " buscarProductos.html.twig " throughout the controller. The problem is that I can do it with php , (is more , in the example I did in php but I put .html.twig ) and the driver actually performs the query and passes it to the template. I wonder if " SearchProducts " I have to do in twig and how, or if you have to do in php and as I do. Forgive me if I do not understand is that I am Argentine and I can hardly communicate with you . Thank you

First of all, do not use mysql_connect : it's deprecated; you should always use Doctrine.

The AJAX call should call the url /products which should be the GET action buscarProductosAction ; you do not need the buscarProductos.html.twig view because you can do something like that inside the action:

<?php

// Namespace definition...

use Symfony\Component\HttpFoundation\JsonResponse;

// Controller class definition...

public function buscarProductosAction(){
    $em = $this->getDoctrine()->getManager();
    $productos = $em->getRepository('ProyectoAdminBundle:Catalogo')->findAll;

    return new JsonResponse(array('productos' => $productos));
}

Check out the official documentation about the JsonResponse class.

PS: Using php code inside a Twig file is totally wrong; you should read and learn the official documentation about templating .

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