Send data by ajax to controller - symfony

1

I am developing a web management system of shifts with symfony 3.4, jquery and ajax. In a form, the user selects a location and a date and must press a button to obtain the available shifts. I can not get the response from the server or the order is not running. It's the first time I've applied ajax.

The script that should send me the data by POST is the following:     

    //AJAX CON JQUERY
    $("#actualizar").on("click",consultarTurnos);

function consultarTurnos()
    {
        var sede = $("#sede").val();
        var fecha = $("#fecha").val();
$.ajax
        ({
            method: 'GET',
            url: '/turnos',
            data: datos,
            dataType: 'json',
            success: function (respuesta)
            {
               // alert('la respuesta es ' + respuesta); 
                $("#respuesta").html(data); 
            },
            error : function(xhr, status) 
            {
                alert('hay error');
                //alert('ERROR -> '. status);
            }

        });



    }

</script>

The html code is as follows:

               <div class="col-lg-4 col-md-4">
                            <select class="form-control" 
                                    name="sede" 
                                    id="sede"
                                    required=""
                                    onchange="guardarSede();">
                                <option disabled selected hidden>Seleccione la sede</option>
                                <option value="1">Predio UNL - ATE</option>
                                <option value="2">Rectorado</option>
                                <option value="3">Esperanza</option>
                            </select>
                        </div>
                        <div class="col-lg-4 col-md-4">
                                        <input class="form-control"
                                               type="text" 
                                               id = "datepicker"
                                               required=""
                                               placeholder="Seleccione la fecha"
                                               onchange="guardarFecha();"
                                               disabled
                                               />

                           <textarea
                                    name="fecha" 
                                    id="fecha"
                                    style = "display:none"
                                    onchange="habilitarTurno();">
                           </textarea>

                                        <!--  -->
                       </div>

<div class="col-lg-2 col-md-2">
                        <button class="btn btn-default"
                                name ="actualizar"
                                id="actualizar"
                                type="button">Actualizar </button>
                    </div>

The method that should receive the information and respond in json format is the following:

 /**
 * @Route("/turnos",name="turnos")
 */
public function buscarTurnos(Request $request)
{
    //var_dump($_GET);
    if($request->isXmlHttpRequest())
    {
        $sede = $request->request->get('sede');
        $fecha = new \DateTime($request->request->get('fecha'));

        $db = $this->getDoctrine()->getEntityManager();
        $qb = $db->createQueryBuilder();

        //escribo la consuLta
        $qb->select('t.dia,t.horario,t.cupo')
           ->from('ComensalesBundle:Turno','t')
           ->where('t.dia = :fecha')
           ->andWhere('t.sede = :sede')
           ->setParameter('fecha',$fecha)
           ->setParameter('sede',$sede)
           ;
        //genero
        $q = $qb->getQuery();
        //consulto
        //$resultado = $q->getResult();
        $resultado = $q->getArrayResult();
        //retorno
        return new JsonResponse($resultado);
    }
    return $this->redirect($this->generateUrl('final'));
}

By entering the browser console, it shows the following: From what I see, it is being sent by get the information but is not getting the response from the server.

The mysql query for searchingTurns () works correctly and the method returns the response in json format as expected. I guess the error is in how I use ajax with jquery. Any collaboration will be eternally grateful. regards Cristian

    
asked by Cristian Budzicz 17.06.2018 в 23:39
source

1 answer

0

After reviewing your code a bit, I think you've forgotten something very timely:

var sede = document.getElementById('sede'); //Aquí cambiaría por $("#sede") pero aún sin eso debería funcionar
var fecha = document.getElementById('fecha'); //Aquí cambiaría por $("#fecha") pero aún sin eso debería funcionar
var datos = {};
datos.sede = sede; //Aquí debería ser sede.val()
datos.fecha = fecha; //Aquí debería ser fecha.val()
alert(datos);

I hope it serves you and if not, you tell me how it was to see what else it could be.

Something else that I think you should modify is here, in the controller method section:

    $sede = $request->request->get('sede'); //Aquí yo uso $request->query->get('sede')
    $fecha = new \DateTime($request->request->get('fecha')); //Y aquí sería $request->query->get('fecha'), posteriormente la conversión a date

Finally, this line of code does not know if it is related to another method since it has a simple view that seems to overwrite the return of the if of the request.

return $this->redirect($this->generateUrl('final'));

In this part I'm not entirely sure, since I do not usually use annotations but rather a single global configuration routing file.

It should be noted that the suggestions I am giving you are based on 100% functional code, since I also use symfony 3.4.10 and 4 to develop.

    
answered by 18.06.2018 / 18:21
source