Request ajax - Query parameter

2

In a page I have this field filled with the value "SP"

<input id="campo" value="SP">

In php I have parameter

<?php
echo $_POST['estado'];
?>

To process this field via ajax I would use

var valor=$('#campo').val();

in the ajax request,

data: {estado: valor},

What I want is to pass this 'state' parameter also inside a variable

var string="estado";

so that in the ajax request it looks like this:

data: {string : valor},

My code

    <script type="text/javascript">
    $(document).ready(function () {
    var string="estado";
    var valor=$("#campo").val();
    ajsjax(string,valor);

    });
    </script>

function ajsjax(string,valor){
    $.ajax({
    type: "POST",
    dataType: "html",
    url: "postos/cadastro_pegar_items.php", 
    data: {string : valor} , //as informações nao chegam aqui da forma correta
    success: function(data){
        alert(data);
    }});
}
    
asked by anonymous 12.11.2018 / 16:22

3 answers

2

With the JSON notation you can not assign the key name dynamically, what you can do is

function ajsjax(string,valor) {
    let data = {};
    data[string] = valor;

    $.ajax({
        type: "POST",
        dataType: "html",
        url: "postos/cadastro_pegar_items.php", 
        data: data,
        success: function(resposta) {
            alert(resposta);
        }
    });
}
    
12.11.2018 / 16:31
0
var valor_1 = "estado";
var valor_2 = "SP";

<script type="text/javascript">
    $(document).ready(function () {
      ajsjax(valor_1, valor_2);
    });
</script>

function ajsjax(valor_1, valor_2){
    $.ajax({
    type: "POST",
    dataType: "html",
    url: "postos/cadastro_pegar_items.php", 
    data: {string : valor_2},
    success: function(data){
        alert(data);
    }});
}
    
12.11.2018 / 16:32
0

You can pass an object directly to your function , for example:

function ajsjax(campoParametro, valor) {
        var dados = {};
        dados[campoParametro]=valor;

        $.ajax({
        type: "POST",
        dataType: "html",
        url: "postos/cadastro_pegar_items.php", 
        data: dados,
        success: function(resposta) {
            alert(resposta);
        }
    });
}

Then you can call function as follows:

<script type="text/javascript">
    $(document).ready(function () {

        var campoParametro = "estado";
        var valor = $("#campo").val();

        ajsjax(campoParametro, valor);

    });
</script>

So I understand you want function ajsjax to be dynamic, if you want to pass another value on another page, just create the object with the property with another name.

    
12.11.2018 / 18:30