It does not show json values

0

I am trying to print some values that I send by post to a php script and I must return the sum of the two sent values, I have already proven that the php is receiving the values and that the json is storing the values.

This is html code:

<html>

<head>
  <meta charset="utf-8">
  <title>Ingreso a control de territorios</title>
  <script>
    function rresult() {
      $.post("r.php", $("#formulario").serialize(), function(resultado) {
        $("#formulario input[name=caja1]").val(resultado.caja1);
        $("#formulario input[name=caja2]").val(resultado.caja2);
        $("#formulario input[name=caja3]").val(resultado.caja3);
      }, "json");
      return false;
    }
  </script>
</head>

<body>
  <form method="post" name="formulario" id="formulario" onsubmit="return rresult()">
    <input type="text" name="caja1" id="caja1" value="<?php echo $caja1 ?>" />
    <input type="text" name="caja2" id="caja2" value="<?php echo $caja2 ?>" />
    <button type="submit">Enviar</button><br/>
    <input type="text" name="caja3" id="caja3" value="<?php echo $caja3 ?>" />
  </form>
</body>

</html>

and this is the php code:

<?php
$caja1 = $_POST['caja1'];
$caja2 = $_POST['caja2'];
$caja3 = $caja1 + $caja2;
echo json_encode(array("caja1"=>$caja1, "caja2"=>$caja2, "caja3"=>$caja3));
?>

I do not know what else to do to pass the values to the form.

    
asked by sebastian valencia 02.10.2017 в 22:50
source

1 answer

0

Surely, the value you are returning r.php , even if it is a string in (string emphasis) is not a JSON object. This may be because the $.post() function could not parse the answer in JSON format (see field dataType ) , and that r.php does not have headers indicating that is responding in JSON format .

There are two ways to solve this problem:

Method 1

We can change the r.php file to add a header to the response, establishing that the content to be displayed is in application/json format:

<?php
$caja1 = $_POST['caja1'];
$caja2 = $_POST['caja2'];
$caja3 = $caja1 + $caja2;
header('Content-Type: application/json'); // Establecer encabezado
echo json_encode(array("caja1"=>$caja1, "caja2"=>$caja2, "caja3"=>$caja3));
?>

Method 2

We can modify the call $.post() to add a forced pairing of the answer of the call:

$.post("r.php", $("#formulario").serialize(), function(resultado) {
    // Forzar el parseo de la respuesta
    if(typeof resultado !== "object") resultado = JSON.parse(resultado);

    $("#formulario input[name=caja1]").val(resultado.caja1);
    $("#formulario input[name=caja2]").val(resultado.caja2);
    $("#formulario input[name=caja3]").val(resultado.caja3);
  }, "json");
    
answered by 26.10.2018 в 21:16