Return two data with AJAX and JSON

1

I have a form that was valid through AJAX. I need ajax (from the file va_registro.php) to return me two data at the same time, so I'm using JSON. I can not get back my data.

registro.php - > This is the Form

 <!--Formulario de registro-->
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" id="formulario">
        <!-- En este span recibo las respuestas de Ajax -->
        <!--En este span recibo los posibles mensajes de error desde ajax-->
        <span id="mensaje"></span>
        <!--En este input recibo desde ajax la comprobacion de si hay errores o no-->
        <input type="hidden" name="ajax" id="ajax">

        <h2>Regístrate</h2>
        <?php if(!empty($errores[5])){echo $errores[5];} ?>
        <p>Usuario &nbsp;<input type="text" name="usuario" id="usuario" value="<?php echo $usuario ?>" onBlur="validarFormulario()" required>
        <?php if(!empty($errores[0])){
                 echo $errores[0];
              }else{
                 echo '<span id="error1"></span>';
              }
        ?></p>
        <p>Contraseña &nbsp;<input type="password" name="pwd" id="pwd" value="<?php echo $pwd ?>" onBlur="validarFormulario()" required>
        <?php if(!empty($errores[1])){echo $errores[1];}
              if(!empty($errores[4])){echo $errores[4];
              }else{
                  echo '<span id="error2"></span>';
              }
        ?></p>
        <p>Contraseña &nbsp;<input type="password" name="pwd2" value="<?php echo $pwd2 ?>"  onBlur="validarFormulario()" required>
        <?php if(!empty($errores[2])){echo $errores[2];} ?></p>
        <p>Email &nbsp;<input type="text" name="email" id="email" value="<?php echo $email ?>" onBlur="validarFormulario()" required>
        <?php if(!empty($errores[3])){echo $errores[3];
              }else{
                 echo '<span id="error3"></span>';
              }
        ?></p>

        <p><input type="submit" name="registrar" value="Registrarse"></p>
     </form>

val_registro.js - > It is assumed that through data.respuesta and data.codigo should access the positions of the array created by JSON

function validarFormulario(){
var dataString = $('#formulario').serialize();  
jQuery.ajax({
    type: "POST",
    //url desde dónde espero una respuesta
    url: "validaciones/val_registro.php", 
    data: dataString,

    dataType: "JSON",
    success: function (data) {
        $("#mensaje").html(data.respuesta);
        $("#ajax").val(data.codigo);
    },
});

}

val_registro.php - > From here I receive the answers

<?php
//Creo las variables
$usuario=$_POST['usuario'];

    if(strlen($usuario)<3){
        $mensaje= array('codigo' => 1, 'respuesta' => "<script>$('#error1').html('El minimo permitido son 3 caracteres')</script>");
        //header('Content-type: application/json; charset=utf-8');
        echo json_encode($mensaje);
        exit();
    }else{
        $mensaje= array('codigo' => 0, 'respuesta' => "<script>$('#error1').html('BIEEEN')</script>");
        //header('Content-type: application/json; charset=utf-8');
        echo json_encode($mensaje);
        exit();
    }

 }
?>

It is showing the entire array, and also, what is in the "answer" position shows it as empty. This is what I get:

{"codigo":1,"respuesta":"
    
asked by Inca 05.05.2018 в 18:59
source

2 answers

1

The problem is that you have HTML code in the value that you will pass to json_encode and then the result will not always be the expected one. As suggested by asachanfbd in your response from the site in English , what you should do is tell json_encode that you are going to pass text with HTML code and quotes to escape them correctly.

Something that applied to your case would look like this:

echo json_encode($mensaje, JSON_HEX_QUOT | JSON_HEX_TAG);

Now, maybe you should consider changing the code a bit to not return HTML but only the message and apply it in JavaScript, instead of passing the JavaScript that should be executed (which may not be a good idea).

Then val_registro.php would be something like this:

<?php
//Creo las variables
$usuario=$_POST['usuario'];

    if(strlen($usuario)<3){
        $mensaje= array('codigo' => 1, 'respuesta' => "El minimo permitido son 3 caracteres'");
        //header('Content-type: application/json; charset=utf-8');
        echo json_encode($mensaje);
        exit();
    }else{
        $mensaje= array('codigo' => 0, 'respuesta' => "BIEEEN");
        //header('Content-type: application/json; charset=utf-8');
        echo json_encode($mensaje);
        exit();
    }

}

And in the val_registro.js you would have something like this:

function validarFormulario(){
var dataString = $('#formulario').serialize();  
jQuery.ajax({
    type: "POST",
    //url desde dónde espero una respuesta
    url: "validaciones/val_registro.php", 
    data: dataString,

    dataType: "JSON",
    success: function (data) {
        $('#error1').text(data.respuesta);
        $("#ajax").val(data.codigo);
    },
});

}
    
answered by 05.05.2018 в 22:40
0

I think what's missing is JSON.parse ()

function validarFormulario(){
var dataString = $('#formulario').serialize();  
jQuery.ajax({
  type: "POST",
  //url desde dónde espero una respuesta
  url: "validaciones/val_registro.php", 
  data: dataString,

  dataType: "JSON",
  success: function (data) {
      json = JSON.parse(data);
      $("#mensaje").html(json.respuesta);
      $("#ajax").val(json.codigo);
    },
  });

}
    
answered by 05.05.2018 в 19:16