Ajax function in edit client controller

34 Views Asked by At

In my edit clients window I will implement a select with ajax that will update the municipalities when selecting a department. However, when the ajax is executed, the information that returns is literally the script that I use in the controller. Below is the script code in edit-clientController:

<?php
if ($_SESSION['user']['ordenes'] == 1) {
  if (count($_POST) > 0) {
    if (isset($_POST['nombres']) && isset($_POST['apellidos']) && isset($_POST['direccion']) && isset($_POST['telefono']) && isset($_POST['nit']) && isset($_POST['genero']) && isset($_POST['correo'])) {
      $nombres = trim(strtoupper($_POST['nombres']));
      $apellidos = trim(strtoupper($_POST['apellidos']));
      $direccion = trim($_POST['direccion']);
      $telefono = trim($_POST['telefono']);
      $nit = trim($_POST['nit']);
      $genero = $_POST['genero'];
      $correo = trim($_POST['correo']);
      if ($nit == '') {
        $nit = NULL;
      }
      if ($nombres == '' || $apellidos == '') {
        echo '<div class="alert alert-danger alert-dismissable">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times-circle-o"></i></button>
                        <b>Error:</b> Rellene todos los campos.
                    </div>';
        exit;
      } else {
        require_once 'models/clienteModel.php';
        $e = new Cliente();
        $update = $e->updateCliente($idItem, $nombres, $apellidos, $nit, $telefono, $direccion, $correo, $genero);
        $e = null;

        if ($update == true) {
          echo '
                    <script>
                        $(location).attr("href","' . BASE_DIR . 'editar-cliente/' . $idItem . '-' . slug($nombres) . '/update");
                    </script>
                ';
        } else {
          echo '<div class="alert alert-danger alert-dismissable">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times-circle-o"></i></button>
                        <b>Error:</b> No se pudo actualizar el registro, recarge la p&aacute;gina e int&eacute;ntelo nuevamente.
                    </div>';
        }
      }
    }
  } else {
    require_once 'models/clienteModel.php';
    $c = new Cliente();
    $cliente = $c->getCliente($idItem);
    $c = null;

    $c = new Cliente();
    $tipos = $c->getTipos();
    $c = null;

    $c = new Cliente();
    $departamento = $c->getDepartamentos();
    $c = null;

    if (count($cliente) > 0) {
      require_once 'views/header.php';
      require_once 'views/clientes-editar.php';
      require_once 'views/footer.php';
    }
  }
} else {
  require_once 'views/404.php';
}
?>

<script>
  var selectElement = document.getElementById("departamentos");
  var lastSearchTerm = "";

  var selectedMun = $("municipio").val();

  function loadMunicipios() {
    var selectedDepartamento = $("#departamento").val();

    if (selectedDepartamento !== lastSearchTerm) {
      lastSearchTerm = selectedDepartamento;

      $("#municipios").prop("disabled", true).attr("placeholder", "Cargando...");
      $.ajax({
        url: 'ClientesEditarMunicipios',
        type: "POST",
        data: {
          finca: selectedDepartamento
        }
      }).done(function(response) {
        // No es necesario dividir la cadena, ya que recibes un array directamente
        updateMunicipiosDropdown(response);
        console.log(response);

        $("#municipio").prop("disabled", false).attr("placeholder", "Municipio");
      }).fail(function(jqXHR, textStatus, errorThrown) {
        console.error("Error en la llamada AJAX:", textStatus, errorThrown);
        console.log("Respuesta del servidor:", jqXHR.responseText);
      });
    }
  }

  function updateMunicipiosDropdown(municipiosList) {
    // Verificar si municipiosList está definido y no es nulo
    if (municipiosList) {
      // Intentar parsear la cadena JSON
      try {
        var parsedData = JSON.parse(municipiosList);

        if (parsedData.success && parsedData.data.length > 0) {
          var municipios = parsedData.data;

          $("#municipio").empty();

          for (var i = 0; i < municipios.length; i++) {
            var idGenerico = municipios[i]["ID_GENERICO"];
            var nombre = municipios[i]["NOMBRE"];

            $("#municipio").append($('<option>', {
              value: idGenerico,
              text: nombre
            }));
          }
        } else {
          console.error("La respuesta no contiene datos válidos.");
        }
      } catch (error) {
        console.error("Error al parsear la lista de municipios como JSON:", error);
      }
    } else {
      console.error("La lista de municipios no está definida o está vacía.");
    }
  }


  // Evento para manejar la selección en "departamentos"
  $("#departamento").on("change", function() {
    loadMunicipios();
  });
</script>

This script was tested in another section and works normally. The URL code: "CustomersEditMunicipalities" is as follows:

<?php
date_default_timezone_set('America/Guatemala');

if (isset($_POST['finca'])) {
    $buscar = $_POST['finca'];
    require_once 'models/clienteModel.php';
    $p1 = new Cliente();
    $resultados = $p1->getMunicipios($buscar);
    $p1 = null;
    error_log(print_r($resultados));
    header('Content-Type: application/json');
    echo json_encode($resultados);
    exit;
}

What is expected is that it returns a json with the appropriate format to be able to go through it in the array and be able to iterate it in the select called #municipios, but what it prints in the console "console.log(response)" is this:

<script>
  var selectElement = document.getElementById("departamentos");
  var lastSearchTerm = "";

  var selectedMun = $("municipio").val();

  function loadMunicipios() {
    var selectedDepartamento = $("#departamento").val();

    if (selectedDepartamento !== lastSearchTerm) {
      lastSearchTerm = selectedDepartamento;

      $("#municipios").prop("disabled", true).attr("placeholder", "Cargando...");
      $.ajax({
        url: 'ClientesEditarMunicipios',
        type: "POST",
        data: {
          finca: selectedDepartamento
        }
      }).done(function(response) {
        // No es necesario dividir la cadena, ya que recibes un array directamente
        updateMunicipiosDropdown(response);
        console.log(response);

        $("#municipio").prop("disabled", false).attr("placeholder", "Municipio");
      }).fail(function(jqXHR, textStatus, errorThrown) {
        console.error("Error en la llamada AJAX:", textStatus, errorThrown);
        console.log("Respuesta del servidor:", jqXHR.responseText);
      });
    }
  }

  function updateMunicipiosDropdown(municipiosList) {
    // Verificar si municipiosList está definido y no es nulo
    if (municipiosList) {
      // Intentar parsear la cadena JSON
      try {
        var parsedData = JSON.parse(municipiosList);

        if (parsedData.success && parsedData.data.length > 0) {
          var municipios = parsedData.data;

          $("#municipio").empty();

          for (var i = 0; i < municipios.length; i++) {
            var idGenerico = municipios[i]["ID_GENERICO"];
            var nombre = municipios[i]["NOMBRE"];

            $("#municipio").append($('<option>', {
              value: idGenerico,
              text: nombre
            }));
          }
        } else {
          console.error("La respuesta no contiene datos válidos.");
        }
      } catch (error) {
        console.error("Error al parsear la lista de municipios como JSON:", error);
      }
    } else {
      console.error("La lista de municipios no está definida o está vacía.");
    }
  }


  // Evento para manejar la selección en "departamentos"
  $("#departamento").on("change", function() {
    loadMunicipios();
  });
</script>

Which is practically the entire script after the edit-clientController code, but I don't understand why it takes that as a "response". What it should return to me (and returns in another section) is an array in json format which I can go through and transform it into a select

I tried to place an "exit" before the else with which I initialize the view, but now it does not directly reach the controller that complements the ajax. If necessary I can share the controller where the ajax function works correctly.

1

There are 1 best solutions below

0
Jazer Salazar On

It's most likely you have an error or returning too many things at once in your ClientesEditarMunicipios endpoint.

The best way is to isolate the issue and figure out which line is causing it.

<?php

date_default_timezone_set('America/Guatemala');

if (isset($_POST['finca'])) {
    // $buscar = $_POST['finca'];
    // require_once 'models/clienteModel.php';
    // $p1 = new Cliente();
    // $resultados = $p1->getMunicipios($buscar);
    // $p1 = null;
    $resultados = [
        'result array element 1',
        'result array element 2',
        'result array element 3',
        'result array element 4',
    ];
    // error_log(print_r($resultados));
    // header('Content-Type: application/json');
    echo json_encode($resultados);
    exit;
}