Search code examples
phparraysjsonajaxsymfony

how to show an array using Ajax and Symfony


i am trying to show a consult which have an array with arrays in symfony using Ajax and json, this is my ajax's script :

    <script>
    var boton=document.getElementById("form_Boton");
    function ajax() {
        var nombre=$('#form_nombre').val();
        $.ajax({
            type: 'POST',
            url: "{{ path('buscar_porCriterio') }}",
            data: ({nombre: nombre}),
            dataType:"json",
            beforeSend:function () {
                alert("enviará a: "+nombre);
            },

            success:function (resp) {
                if(resp!=""){
                    $('#resultados').html(resp["nombre"]+" "+resp["apellido"]+" "+resp["residencia"]);
                }
                if(resp==""){
                    alert("NO SE ENCONTRO NADA");
                }


            }
        })
    }
    boton.addEventListener("click",ajax);

</script>

And this is my controller:

public function PorCriterioAction(Request $request){
    if(!$request->isXmlHttpRequest())
    {
        throw new Exception("Error, NO ES AJAX");
    }
    $nombre=$request->request->get('nombre');
    $em=$this->getDoctrine()->getManager();
    $encontradas=$em->getRepository('FormulariosBundle:persona')->findBynombre($nombre);
    if ($encontradas == null) {
        $response = new Response("VACIO  " . $nombre . " Sorry");
        return $response;
    }
    else{
        $persona_encontrada = (array("id" => $encontradas->getId(),
            "nombre" => $encontradas->getNombre(),
            "apellido" => $encontradas->getApellido(),
            "residencia" => $encontradas->getResidencia()
        ));
        $response= new JsonResponse($persona_encontrada);
        return $response;}}

what i need is get all data from my DB whose name be $nombre, and show every data in my div 'resultados'. but. when i realize my search, symfony show me this exception: Exception

my question is: How can i do to pass every data of that consult to my div 'resultados'?

as you see, i want to show such consult in a div whose id is "resultados" but does not work, can you help me please? i am a beginner in symfony and i have to make this University Proyect and finish my study, thanks for your answer

EDIT # 2

this is the change to my controller:

public function PorCriterioAction(Request $request){
    if(!$request->isXmlHttpRequest())
    {
        throw new Exception("Error, NO ES AJAX");
    }
    $nombre=$request->request->get('nombre');
    $em=$this->getDoctrine()->getManager();
    $encontradas=$em->getRepository('FormulariosBundle:persona')->findBynombre($nombre);
    if ($encontradas == null) {
        $response = new Response("VACIO  " . $nombre . " Sorry");
        return $response;
    }
    else{
        foreach ($encontradas as $Item){
            $persona_encontrada = (array("id" => $Item->getId(),
                "nombre" => $Item->getNombre(),
                "apellido" => $Item->getApellido(),
                "residencia" => $Item->getResidencia()
            ));
            array_push($persona_encontrada,$Item);
        }
            $response= new JsonResponse($persona_encontrada);

        return $response;
    }
}

is this what you need? responseText


Solution

  • I believe $encontradas is a results set so try this:

    foreach( $encontradas as $item){
        $persona_encontrada = (array(
            "id" => $item->getId(),
            "nombre" => $item->getNombre(),
            "apellido" => $item->getApellido(),
            "residencia" => $item->getResidencia()
        ));
    }
    

    Let us know the result.


    EDIT #2

    I see the problem. Since it iterates through the array, you want $persona_encontrada to be an array and then use the PHP array_push to add array elements to it. You could do it like so:

    $persona_encontrada = array();
    
    foreach( $encontradas as $item){
        $element = array(
            "id" => $item->getId(),
            "nombre" => $item->getNombre(),
            "apellido" => $item->getApellido(),
            "residencia" => $item->getResidencia()
        );
    
        array_push( $persona_encontrada, $element);
    }
    

    By the way, although this will work for you, it might not be the best way to do something like this. But it will work.