Pregunta

How can create a string in JSON after a mysql select:

$ritorno = '{"Prodotto":'.$riga['Prodotto'].',"Prezzo":'.$riga['Prezzo'].'}'

and return this:

{"Prezzo":24.00,"Prodotto":Chiavetta Usb Moskeyto 8 gb}

But I can't insert in my input field

Jquery

function chiama(elemento){
      var $code_bar = $("#code_bar").val();

      $.post("return.php", 
            { code_bar: $code_bar },
      function(data) {
            $("#Prodotto").val(data.Prodotto);
            $("#Prezzo").val(data.Prezzo);
    }

      , "json");
}
¿Fue útil?

Solución

You can use json_encode to turn php array to json formatted string.

Example from manual:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
// prints {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

Otros consejos

If you dont have any other element on that $riga array then you can just do

echo json_encode($riga)

and if you have other elements on that array and just want those two to be json encoded then you can use

echo json_encode(array(
    "Prodotto" => $riga['Prodotto'],
    "Prezzo" => $riga['Prezzo']

   ));

The reason your one is not working is because you dont have the string value in quotes Which is required for valid JSON

You have to do it like

$ritorno = '{"Prodotto":"'.$riga['Prodotto'].'","Prezzo":'.$riga['Prezzo'].'}';

If you insist to go in your way.

But using json_encode is better.

Example Code: http://codepad.org/r6D7z9TF

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top