Random error when traversing a json in a javascript function

2

I have an error of: data [key] .forEach is not a function. but it is totally random, sometimes perfectly executes others not.

This is my code:

<script type="text/javascript">
$(document).ready(function() {
    var table = $('#example').DataTable({
        "pagingType": "full_numbers",
        "lengthMenu": [[5], [5]]
    });

    $('#example tbody').on('click', 'tr', function () {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    });

    $('#button').click( function () {
        var dias=[];
        var mydata = table.row('.selected').data();
        var idpac=mydata[0];
        // VERIFICO EL CHECK DE LOS DIAS A ELEGIR
        if($("#lunes").is(':checked')) {
            dias.push("lunes");
        }
        if($("#martes").is(':checked')) {
            dias.push("martes");
        }
        if($("#miercoles").is(':checked')) {
            dias.push("miércoles");
        }
        if($("#jueves").is(':checked')) {
            dias.push("jueves");
        }
        if($("#viernes").is(':checked')) {
            dias.push("viernes");
        }

         var nsesiones=$("#nsesiones")[0].value;
        var diag=$("#diagnosticoSelect")[0].value;


        $.ajax({
            type: 'POST',
            url: 'turno/calculo',
            data:{data:JSON.stringify(dias),nsesiones:nsesiones,idpac:idpac},
            success: function(response) {
              createSelects(response,idpac,diag);

            }
            });

    } );







    function createSelects(data,idpac,diag) {
        var i=1;
        var f = document.createElement("form");
        f.setAttribute('method',"post");
        f.setAttribute('action',"turno/confirmar");
        document.getElementById("result").appendChild(f);

        data=JSON.parse(data);
        for(let key in data) {
            var wrapper = createWrapper();
            var input = createElement('input');
            input.setAttribute('name',"dia"+i);
            input.setAttribute('readOnly',true);
            var select = createElement('select');
            select.setAttribute('name',"horario"+i);

            input.value = key;
            data[key].forEach(function(hour) {
                var option = createElement('option');
                option.setAttribute('value', hour);
                option.textContent = hour;
                select.appendChild(option);
            });
            wrapper.appendChild(input);
            wrapper.appendChild(select);
            f.appendChild(wrapper);

            i++;
        }
        var input1 = document.createElement("input");

        input1.setAttribute("type", "hidden");

        input1.setAttribute("name", "Cantidad");
        input1.setAttribute("value", i-1);
        f.appendChild(input1);
        var input2 = document.createElement("input");
        input2.setAttribute("type", "hidden");
        input2.setAttribute("name", "paciente");
        input2.setAttribute("value",idpac );
        f.appendChild(input2);
        var input3 = document.createElement("input");
        input3.setAttribute("type", "hidden");
        input3.setAttribute("name", "diag");
        input3.setAttribute("value",diag );
        f.appendChild(input3);
        var s = document.createElement("input"); //input element, Submit button
        s.setAttribute('type',"submit");
        s.setAttribute('value',"Submit");
        f.appendChild(s);


    }

    function createWrapper() {
        var section = createElement('section');
        section.classList.add('input-group');
        return section;
    }

    function createElement(tagName) {
        return document.createElement(tagName);
    }


});

and in / I have calculation:

public function calculo()
{

    $config = $this->configuracion_model->ver();
    foreach ($config as $row) {
        $franjaConfig = $row->franja;
        $consult = $row->cantidad_consultorios;
    }
    $franja1 = ["08:00:00", "08:30:00", "09:00:00", "09:30:00", "10:00:00", "10:30:00", "11:00:00", "11:30:00"];
    $franja2 = ["12:00:00", "12:30:00", "13:00:00", "13:30:00", "14:00:00", "14:30:00", "15:00:00", "15:30:00"];
    $franja3 = ["16:00:00", "16:30:00", "17:00:00", "17:30:00", "18:00:00", "18:30:00", "19:00:00", "19:30:00"];
    switch ($franjaConfig) {
        case 123:
            $franja = array_merge($franja1, $franja2, $franja3);
            break;
        case 12:
            $franja = array_merge($franja1, $franja2);
            break;
        case 13:
            $franja = array_merge($franja1, $franja3);
            break;
        case 23:
            $franja = array_merge($franja2, $franja3);
            break;
        case 1:
            $franja = $franja1;
            break;
        case 2:
            $franja = $franja2;
            break;
        case 3:
            $franja = $franja3;
            break;
    }
    $franjaTotal = array();
    foreach ($franja as $value) {
        for ($i = 1; $consult >= $i; $i++) {
            array_push($franjaTotal, ($value ."-". $i));
        }

    }
    $data = json_decode($_POST['data'], true);
    $nsesiones = json_decode($_POST['nsesiones'], true);
    $paciente = $_POST['idpac'];

    $i = 0;
    $j = 1;
    $franjaPivot = $franja;
    $response = array();
    $franjaObtenidaBD = array();


    while ($nsesiones > $i) {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        setlocale(LC_TIME, '');
        //PRIMERO CONTROLO QUE EL DIA A BUSCAR ESTE EN EL ARRAY DEL LISTADO DE DIAS POSIBLES
        if (in_array(utf8_encode(strftime("%A", strtotime("+" . $j . "days"))), $data)) {
            $resultadoExistePac = $this->turno_model->existePaciente(date('Y-m-d', strtotime("+" . $j . "days")), $paciente);
            $listaHorarioTurno = $this->turno_model->listadoTurnos(date('Y-m-d', strtotime("+" . $j . "days")));
            $dia = (date('Y-m-d', strtotime("+" . $j . "days")))."/".utf8_encode(strftime("%A", strtotime("+" . $j . "days")));
            // PREGUNTO SI HAY TURNOS LIBRES
            if ($listaHorarioTurno != 0 and $listaHorarioTurno != 1) {
                // EN ESTE CASO HAY ALGUNOS TURNOS LIBRES
                //Pregunto si el paciente ya tiene turnos
                if ($resultadoExistePac == 0) {
                    //Si no tiene turnos
                    //Entonces saco del array los horarios que hay cargados en la base, en uso. y creo un array con el que asocio los dias
                    //y los posibles horarios para elegir
                        foreach ($listaHorarioTurno as $row) {
                            $horario = $row->desde;
                                 for ($i = 1; $consult >= $i; $i++) {
                                    array_push($franjaObtenidaBD, ($horario ."-". $i));
                                    }
                        }
                    $resultado = array_diff($franjaTotal, $franjaObtenidaBD);
                    $response[$dia] = $resultado;
                 }
                //termina el if de paciente no tiene turno

            } elseif ($listaHorarioTurno == 0) {
                //muestro la franja entera por q esta to-do libre
                $response[$dia] = $franjaTotal;
                $i++;
            }

        }
        $j++;

    }
    $respues=json_encode($response);

}

If someone can give me a hand, thank you very much

    
asked by Matias Blanco 26.10.2016 в 23:23
source

2 answers

1

As you saw in the comments, the problem is in the backend, when coding it when returning your json your problem is solved by adding the flag JSON_UNESCAPED_UNICODE .

json_encode($data,JSON_UNESCAPED_UNICODE);
    
answered by 27.10.2016 / 00:42
source
1

The data ( string ) that you are parsing in

data=JSON.parse(data);

contains elements (which references using the key key in data[key] ) that do not have the property forEach

If you want to prevent the execution of your code block from ending suddenly, you can previously work on all the elements of the object data to have the property forEach (it will depend on the logic of your algorithm), or Do something like the following:

    try{
        data[key].forEach(function(hour) {
            var option = createElement('option');
            option.setAttribute('value', hour);
            option.textContent = hour;
            select.appendChild(option);
        });
    }catch(e){
        //maneja el error aqui
    }

Since what you are parsing is a response from the server, you should then also review the logic of the backend algorithm that responds to that AJAX request.

    
answered by 26.10.2016 в 23:43