Pass 2 or more varibles by method get

2
                                                  State                                                       State                                       
    <div class="form-group row">
        <div class="col-5">
            <select class="form-control" name="municipio" id="municipio">
              <option>Municipio </option>
            </select>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-5">
            <select class="form-control" name="parroquia" id="parroquia">
              <option>Parroquia</option>
            </select>
        </div>
    </div>

THIS CODE FILLS STATE AND MUNICIPALITY THROUGH THE ARCHIVE DIRECIONES.JS

$(document).ready(
    function()
{
    cargar_estados();
    $("#estados").change(function(){cargar_municipio();});
    $("#municipio").change(function(){cargar_parroquia();});
    //$("#estados").change(function(){cargar_parroquia();});
    $("#municipio").attr("disabled",true);
    $("#parroquia").attr("disabled",true);
});

function cargar_estados()
{
    $.get("../../otros/cargar-estados.php", 
        function(resultado){
            if(resultado == false)
            {
                alert("Error al cargar Estado");
            }
            else
            {
                $('#estados').append(resultado);           
            }
        }); 
}

function cargar_municipio()
{
    var id_est = $("#estados").val();
    $.get("../../otros/cargar-municipio.php", { id_est:id_est },
        function(resultado)
        {
            //alert(id_est);
            if(resultado == false)
            {
                alert("Error al cargar Municipio");
            }
            else
            {
                $("#municipio").attr("disabled",false);
                document.getElementById("municipio").options.length=1;
                $('#municipio').append(resultado);         
            }
        }

    ); 
}

THE IDEA IS TO PASS THE VARIABLES #state #municipality TO THE PARISH FUNCTION TO THEN BE ABLE TO MAKE THE NECESSARY SQL

<SCRIPT>
function cargar_parroquia()
{
    var id_est = $("#estado").val();
    var id_mun = $("#municipio").val();
    alert(id_est);
    /*$.get("../../otros/cargar-parroquia.php",{id_mun:id_mun}+{ id_est: id_est},
      function(resultado)
        {
            //alert(id_mun);
            //alert(id_est);
        if(resultado == false)
        {
            alert("Error al Cargar parroquia");
        }
        else
        {
            $("#parroquia").attr("disabled",false);
            document.getElementById("parroquia").options.length=1;
            $('#parroquia').append(resultado);         
        }
    });  */
}
</SCRIPT>
    
asked by Yader Yepez 17.01.2018 в 19:43
source

2 answers

0

When it is a GET the parameters should be sent in the query string (URL)

$.get("../../otros/cargar-parroquia.php?id_mun="+id_mun+"&id_est="+id_est,...

    
answered by 17.01.2018 в 21:44
0

I propose a solution based on the following:

  • Use of the $getJSON method, because it will be much easier to recover the data that the server responds to. Now, the server must respond only and exclusively a valid JSON object, which we will read in done of the request.
  • Use of updated code. After jQuery 3, document.ready is considered obsolete. The use of function is recommended. It would have a block like this:

    $(function() {
    
        /*Aquí dentro todas las funciones*/
    
    }); 
    
  • For requests to the server, it is convenient to implement at least one method done and other fail , to report possible errors.

  • We will work with variables, to write a cleaner and readable code

jQuery

$(function() {

    /*Aquí deberían ir todas tus funciones*/

    function cargar_parroquia(){

        var id_est = $('#estado').val();
        var id_mun = $('#municipio').val();
        var data={id_est: id_est, id_mun: id_mun};
        var url='../../otros/cargar-parroquia.php';

        var xhrGet = $.getJSON(url, data);

        xhrGet.done(function(datos) {
            if(datos.error){
                alert('Hubo un error en el servidor: '+datos.error);
            }else{
                /*Prueba*/
                console.log(datos);

                /*
                    *Leemos la respuesta accediendo en un bulce each por nombres de clave
                    *así podemos por ejemplo llenar las option de un select
                    *una tabla, un formulario, o lo que queramos
                    *y añadirlo a algun elemento del DOM
                */
                $.each(datos, function (k, v) {
                    console.log(v.id_mun);
                    console.log(v.municipio);
                });

            }
        });

        xhrGet.fail(function(jqXHR, textStatus) {
            alert('Hubo un error: ' + textStatus);
        });
    }

});

PHP

if( isset($_GET['id_est']) && isset($_GET['id_mun']) ) {    
    /*
        *Aquí lanzas la consulta y almacenas los resultados en un array
        *usando uno de los métodos fetch
        *vamos a suponer que esa variable se llama $arrResultado
        *y tendrá algo así más o menos
    */

    $arrResultado=array(array('id_mun'=>1,'municipio'=>'Municipio 1'), array('id_mun'=>2,'municipio'=>'Municipio 2'));

}else{

    /*Si hay error, creamos un array con la clave "error"*/
    $arrResultado=array('error'=>'Hubo un error: No se pasaron los parámetros en el GET');

}
/*Imprimimos el resultado, cualquiera que sea*/
header('Content-Type: application/json;charset=utf-8');
print_r(json_encode($arrResultado));

IMPORTANT NOTE: Generally, when you build an array of a set of database results, you actually create a JSON array similar to this:

[{
    "id_mun": 1,
    "municipio": "Municipio 1"
}, {
    "id_mun": 2,
    "municipio": "Municipio 2"
}]

The eventual reading in done is not done as a JSON object, you must first access the array, and then the JSON object that is inside.

I hope it helps you. If you have doubts in something, you can ask in comments.

    
answered by 17.01.2018 в 21:57