How to capture the value of a JSON key (from an AJAX) using Jquery?

Asked

Viewed 134 times

0

I have the following AJAX:

$("button[name='btn-editar-marca']").on('click', function(){
    $.ajax({
        type: "GET",
        url: "../ajax/ajax.marcas.php",
        data: {"ajax-params": 2, "Id_Marca": $(this).attr("id")},
        dataType: "JSON",
        success: function(res){
            console.log(res);
            $("input[name='inputCodMarca']").val(res.Id_Marca);
            $("input[name='inputNomeMarca']").val(res.Nome_Marca);
            $("input[name='textareaObsMarca']").val(res.Obs_Marca);
            $("input[name='inputDataCadMarca']").val(res.Data_Cadastro);
            $('#md-editar-marca').modal('show');
        },
        error: function(res){
            if(res.status == 200)
                alert("Erro 200");
            else if(res.status == 404)
                alert("Erro 404");
            else
                alert("Algo de errado não está certo!");
        }
    });
});

The console.log(res) in the middle shows the following return:

inserir a descrição da imagem aqui

When opening it:

inserir a descrição da imagem aqui

When opening "position [0]":

inserir a descrição da imagem aqui

These values that appeared at position 0 are the ones I wish to capture to insert them in inputs, I can even catch them like this:

res[0].Id_Marca
res[0].Nome_Marca

Is this the only way to capture the values? I would like something more "professional", so to speak, some function, something like that, because in this case it is a select that brings only 1 value (selectPorId), so it will only have the position 0 same, but soon less I will have to bring more values, for example: "Select the items of a purchase". Often it will have more than 1 item, so it would have to be something dynamic. How could I replace this res[0].VALORES for something dynamic?

I saw the function JSON.parse() but it did not work, maybe because I do not know use-there or maybe not be the ideal function for case.

  • 1

    That’s how it is. Use [0] There is nothing wrong. Most certain, in fact, would be to return the data in object (and not array) format, through the back-end. Then yes, you could do res.Id_Marca.

  • You can give a res = res[0]

1 answer

0


In case your array has more than 1 element you will need to use the . map() function or even a for going through your array:

res.map((i, j) => {
  console.log(res[j].Id_Marca)
  console.log(res[j].Nome_Marca)
});

So you don’t have to worry about the size of your json’s return.

Browser other questions tagged

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