How to access the elements of a String in Jason format in Javascript

Asked

Viewed 91 times

-1

I cannot print the values contained in a string in Jason format using Javascript in a modal containing multiple definition lists. I imagine it’s some syntax error in the access but I couldn’t solve it.

My scenario here is this:.

Here after the query to the database, I do the conversion through PHP of the variable $found for a string in Jason format as follows:

$veiculo_string_jason = json_encode($found);
echo $veiculo_string_jason;

The content of the variable $veiculo_string_jason is as follows:

{"tipo":"Carro","marca":"Citroen","modelo":"Air Cross Salomon Exclusive 1.6 Flex","alimentacao":"Flex","placa":"ABC1234","cor":"Branco","anofab":"2014","anomod":"2015","chassi":"11111111111111111","renavam":"22222222222","valor_compra":"42000.00","valor_venda":"45500.00","situacao":"Consignado","status":"Ativo"}

The Javascript code that makes the whole interface is this one:

// INTERFACE MODAL viewVeiculo
$(document).ready(function () {
    $(document).on('click', '.view_data', function () {
        var placa = null;
        placa = $(this).attr("placa");
        if (placa !== '') {
            var dados = {
                placa: placa
            };
            $.post('dsVeiculo.php', dados, function (retorna) {
                var veiculo = retorna;
                $("#var0").html(veiculo.tipo);
                $("#var1").html(veiculo.marca);
                $("#var2").html(veiculo.modelo);
                $("#var3").html(veiculo.alimentacao);
                $("#var4").html(veiculo.placa);
                $("#var5").html(veiculo.cor);
                $("#var6").html(veiculo.anofab);
                $("#var7").html(veiculo.anomod);
                $("#var8").html(veiculo.chassi);
                $("#var9").html(veiculo.renavam);
                $("#var10").html(veiculo.valor_compra);
                $("#var11").html(veiculo.valor_venda);
                $("#var12").html(veiculo.situacao);
                $("#var13").html(veiculo.status);
                $('#viewVeiculo').modal('show');
            });
        }
    });
});

Id’s from #var0 to #var13 are definition lists.

<dl class="row mb-0">
  <dt class="col-sm-6 text-right">Tipo:</dt>
  <dd id="var0" class="col-sm-6"></dd>
</dl>

I sought help on these topics but without success.

How to show values stored in JSON in Javascript

How to create Divs within Java and use Json

  • 2

    You need to parse in Sponse. var veiculo = jQuery.parseJSON( retorna );

  • @Igormello made the correction and it worked, now I can access each element of the string.

2 answers

4


JSON formatting is right, alias, if you passed the function json_encode can’t possibly be wrong.

The reason you are not being able to read the properties of this JSON on the user side is probably because your user does not know that the server is returning a JSON, he thinks the server is returning any text.

You can make a console.log in that retorna to check whether this variable actually contains an object, or a string.

Now to parse this string for JSON, you have some options, such as:

1-parse manually on the user side

var veiculo = JSON.parse(retorna);

2- in PHP, include header with the type of content you are returning, thus the jQuery will parse automatically

header('Content-Type: application/json');

3- include the type of the return in the AJAX call itself:

$.ajax({
    url: 'dsVeiculo',
    method: 'POST'
    data: dados,
    dataType: 'json',
    success: function(retorna) {
      // ...
    }
})
  • I made the correction and it worked, now I can access each element of the string.

0

If I pass an object instead of a string, how would I access the data?

The object has this structure:

object(stdClass)[3]
  public 'tipo' => string 'Carro' (length=5)
  public 'marca' => string 'Citroen' (length=8)
  public 'modelo' => string 'Air Cross Salomon Exclusive 1.6 Flex' (length=36)
  public 'alimentacao' => string 'Flex' (length=6)
  public 'placa' => string 'ABC1234' (length=7)
  public 'cor' => string 'Branco' (length=4)
  public 'anofab' => string '2014' (length=4)
  public 'anomod' => string '2015' (length=4)
  public 'chassi' => string '11111111111111111' (length=17)
  public 'renavam' => string '22222222222' (length=11)
  public 'valor_compra' => string '42000.00' (length=8)
  public 'valor_venda' => string '45000.00' (length=8)
  public 'situacao' => string 'Consignado' (length=10)
  public 'status' => string 'Ativo' (length=5)

Browser other questions tagged

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