Return variables to success of ajax request

0

I am trying to return variables within the success of an ajax request to validate that "such a thing" was done within the system, in this case not to let it advance until it adds elements to a list.

$("#saveList").on(\'submit\',(function(e) {         
        e.preventDefault();
        formString = $("#previewList").serialize();
            $.ajax({
                url: "lists/list.php",
                data:  formString,
                type: "GET",
                dataType: "json",
                success: function(data){
                    if(data.valida == "zero"){
                        toastr.warning("Agrega al menos un elemento a la lista");
                    }else{
                        alert("Lista guardada");
                        location.reload(true);
                    }
                },
                error: function(data){
                    console.log("error")
                }
            });
        })
    );

And in the script of lista.php the validation I do it in this way, return a variable with the value of string "zero" and finish the execution of the script:

$result = mysqli_query($link,"SELECT * FROM lists WHERE emp = $idemp");
$count  = mysqli_num_rows($result);
// if there is no rows
if($count == 0){
    $data['valida'] = 'zero';
    echo json_encode($data);
    exit;
}

And when I have elements in the list, I have to create a pdf, but at the moment of printing with the script the pdf the else of the validation in the succes:

}else{
    alert("Lista guardada");
    location.reload(true);
}

It does not work, it does not do the alert and it does not refresh the page, my question is, is there any other way than by json to return script variables to the success of the request to be able to use them within the success?

    
asked by Fernando Garcia 28.07.2018 в 22:50
source

1 answer

0

You have several errors, and good an abstraction of the limited idea. I'll give you an example so you can see how the front and the back can interact harmoniously

On your Javascript

//Con esta instrucción obligas al DOM a buscar el elemento donde se encuentre en tu documento
$(document).on('submit','#saveList',function(e){
  e.preventDefault();
  var formString = $("#previewList").serialize();
  $.ajax({
      url: "lists/list.php",
      data:  formString,
      method: "GET",
      dataType: "json",
      success: function(data){
          //Aquí validas lo que trae el nodo success ( $json['success'] )
          if( !data.success ){
              //Como el JSON trae un mensaje, lo puedes imprimir
              toastr.warning( data.message );
          }

          else{
              //Si te regresa un TRUE entonces ya puedes recargar
              toastr.success( data.message + ' ' + data.data );
              location.reload(true);
          }
      },
      error: function(data){
          console.log("error")
      }
  });
});

Now your PHP, has several errors of syntax and logic, I tried to fix it and "I guess" that should do your server, you can modify it to your liking.

<?php 
//Debemos recuperar primero la variable que llega, no se como se llame en el front, así que
//Modifica esta parte
$idemp = $_REQUEST['idemp'];

//Incluye tu script para la conexión
require 'mi_conexión.php';

//Preparamos un arreglo que es el que contendrá toda la información
$json = array();
$result = mysqli_query($link,"SELECT emp FROM lists WHERE emp = $idemp");
//Validamos que se haya ejecutado bien la consulta
if( !$result ){
  $json['success'] = false;
  $json['message'] = 'La consulta trono';
  $json['data'] = null;
}

else{
  //Validamos que la consulta haya retornado información
  if( mysqli_query_num_rows( $result ) <= 0 ){
    $json['success'] = false;
    $json['message'] = 'Agrega al menos un elemento a la lista';
    $json['data'] = null;
  }

  else{
    //Si hay datos entonces retornas que se guardó la lista
    $json['success'] = true;
    $json['message'] = 'Lista guardada';
    $json['data'] = 'Datos encontados ' . mysqli_query_num_rows( $result );

    //Recuerda siempre limpiar la memoria
    mysqli_free_result( $result );
  }

}
//Liberar la conexión
mysqli_close( $link );

//Retornamos el nuestro arreglo en formato JSON, recuerda agregar el encabezado, es indispensable para el navegador
//Saber que tipo de información estas enviando
header('Content-Type: application/json');
echo json_encode( $json );
?>

Remember to add the script for your database connection.

I hope you serve the example, greetings.

    
answered by 29.07.2018 / 01:49
source