How to take the net value of a select in a JQUERY change?

1

I have the table país and ciudad , the city depends on the country, so I decided dynamically that when I select the country I do change taking the value , in this case the id_pais and that send a% per% code to list the cities that depend on that country ...

the problem is that you are sending me the following: ajax and you are not sending me only the 5 (id_pais=5) ...

I would appreciate the interest and the intention to be able to collaborate ...

CODE

$.ajax({
        url: 'paises',
        type: 'POST',
    })
    .done(function(answer){
        var result= $.parseJSON(answer);

            $('#pais').append('<option disabled selected>-- Seleccione Pais -- </option>');
        for(var i = result.length - 1; i >= 0; i--)
        {
            $('#pais').append('<option value="' + result[i].id_pais + '">' + result[i].nombre_pais+ '</option>');

        }
    })
    .fail(function() {
        console.log("error");
    });

    $('#paises').change(function() {

        var id_pais= $(this).serialize();
        console.log(id_pais);
        $.ajax({
            url: 'ciudades',
            type: 'POST',
            data: {'id_pais' : id_pais},
        })
        .done(function(respuesta) {
            console.log(respuesta);
        })
        .fail(function() {
            console.log("error");
        })
    
asked by JDavid 06.03.2017 в 21:31
source

1 answer

3

Your friend problem is that you are serializing 2 times:

var id_pais= $(this).serialize(); 

returns id_pais: 5, what are you concatenating to next:

{'id_pais' : id_pais}

which would look like this:

{'id_pais' : 'id_pais: 5'} 

Now your solution would be doing it this way:

$.ajax({
    url: 'paises',
    type: 'POST',
})
.done(function(answer){
    var result= $.parseJSON(answer);

        $('#pais').append('<option disabled selected>-- Seleccione Pais -- </option>');
    for(var i = result.length - 1; i >= 0; i--)
    {
        $('#pais').append('<option value="' + result[i].id_pais + '">' + result[i].nombre_pais+ '</option>');

    }
})
.fail(function() {
    console.log("error");
});

$('#paises').change(function() {
    $.ajax({
        url: 'ciudades',
        type: 'POST',
        data: {'id_pais' : parseInt($(this).val())},
    })
    .done(function(respuesta) {
        console.log(respuesta);
    })
    .fail(function() {
        console.log("error");
    });

Lucky Friend.

    
answered by 06.03.2017 / 21:38
source