Change value of an attribute in ajax

0

I have the following query: I want to know if it is possible to use a variable in an attribute in ajax, I do not know if I explain myself, but in the following code I will try to explain:

<script>
function active_change_update(ruta, id, status, campo)
{
    if(status==1 || status==null){
        var estado = 0;
    }else{
        var estado = 1;
    }

    var dato = { 
        'id': id,
        '_token': "{{ csrf_token() }}",
        //por defecto utilizaba active ya que en mi tabla producto esta asi y lo unico que quiero modificar es el valor del active
        //hasta aqui todo bien
        'active': estado
    };

    $.ajax({
        type: "PUT",
        url: ruta,
        dataType: 'json',
        data: dato,
        success:function(data) {
            window.location.reload();
        }
    });
}

As you can see I want to modify the value of the active, but I realized that this function can be used to modify several attributes of other tables, for example the "sold" or "delivered" that are also Boolean. What I want to do is the following:

function active_change_update(ruta, id, status, campo)
{
    if(status==1 || status==null){
        var estado = 0;
    }else{
        var estado = 1;
    }

    //recibo el valor de "campo" que en este caso es "vendido" y quiero pasar ese atributo al json

    var dato = { 
        'id': id,
        '_token': "{{ csrf_token() }}",
        //de esta manera
        campo: estado
    };

    $.ajax({
        type: "PUT",
        url: ruta,
        dataType: 'json',
        data: dato,
        success:function(data) {
            window.location.reload();
        }
    });
}

Absolutely this is not the right way and I have looked for several alternatives, I would be very grateful if you could help me with this. Thank you very much already.

    
asked by MarianoC1993 03.01.2019 в 13:59
source

1 answer

1

First create a dynamic text string, you do it by concatenating the values.

has to be with single quotes as the example shows

then to be able to send your data by ajax you need to convert your string to Json with JSON.Parse()

your code would be in the following way:

function active_change_update(ruta, id, status, campo)
{
    if(status==1 || status==null){
        var estado = 0;
    }else{
        var estado = 1;
    }

    //aqui colocamos la cadena donde concatenas los valores y atributos dinamicos dinamicos

    var cadena = '{ "id": "' + id + '","_token": "1","' + campo + '": "' + estado + '"}'

    //aqui usamos el JSON.Parse para convertir tu cadena a Json

    var dato = JSON.parse(cadena);

    $.ajax({
        type: "PUT",
        url: ruta,
        dataType: 'json',
        data: dato,
        success:function(data) {
            window.location.reload();
        }
    });
}

the result:

  

{id: "1", _token: "1", Status: "1"}

just need to adapt your token.

I hope you help, greetings.

    
answered by 03.01.2019 / 19:17
source