How to send via ajax the value of the selected option in a select?

Asked

Viewed 611 times

-1

I have two selects, one for states and one for cities.

I want to take the value of the select of states with the change event, send it via ajax and recover the cities that has the corresponding value.

The only error that is giving in my code is to say that the variable that send via post is undefined

Follow the codes and the error:

<select name="Estado" id="estado" class="campo selectEstado form-control">
    <option value="">Selecione seu estado</option>
    // Outros options
 </select>

<select name="Cidade" id="cidade" class="campo selectCidade form-control">
    <option value="">Selecione sua cidade</option>
    // Outros options
 </select>


$('#estado').on('change',function(){
        var uf = $("#estado option:selected").val();
        $.ajax({
            type: "POST",
            url: "scripts/retornaMunicipio.php",
            data: uf,
            success:function(data){
            data = $.parseJSON(data);
            $.each(data.retorno, function (i) {
                // código
             });

                                    },
            error:function(data){
            }
        });
    });

File returnMunicipio.php

$uf = $_POST["uf"];
// Esse uf não está sendo definido

Follow the error:

PHP Notice:  Undefined index: uf in C:\inetpub\teste\httpdocs\retornaMunicipio.php on line 15

My only problem is this, this variable $uf is not receiving the value sent by ajax. The file paths are right. How can I resolve this?

1 answer

2


Try this:

     $.ajax({
        type: "POST",
        url: "scripts/retornaMunicipio.php",
        data: {uf: uf},
        success:function(data){
           data = $.parseJSON(data);
           $.each(data.retorno, function (i) {
            // código
           });
        },
        error:function(data){
        }
    });
  • exactly that!

  • Can you explain to me why?

  • 1

    You need to say what you will send and the amount you will send, for example: data: {status: Uf} In this way la in PHP you would get $Uf = $_POST['status'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.