Requisicao ajax - query parameter

Asked

Viewed 73 times

1

on 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 parameter 'state' also within 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);
    }});
}
  • 1

    you want the data be dynamic?

  • Take a look at my answer.

  • This link is blocked here in the company.

3 answers

2


With the JSON notation you cannot 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);
        }
    });
}
  • 1

    Better you edit your question, I don’t understand anything you’re saying. Not to mention you didn’t even mention PHP.

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);
    }});
}

0

You can pass an object directly into 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>

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

  • www.meuposto.ml/2.html

Browser other questions tagged

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