Console error when sending form data using Ajax

0

Friends please I need help I do not know why ajax does not bring me the result of the request when I send data from my form. If someone at least explain to me what is my mistake and what is it about? Thanks.

What I know, is that when I send my data to .php through ajax inserted to the asuario and indeed it does but in my condition where it validates if the query was executed is my variable that awaits the result that I must take to the html, but nothing happens. He does not show me the alert and he still shows me that error when I reload on another page:

My code:

document.getElementById("enviar").onclick = function() {
    RegistrarUsuario();
};

String.prototype.isEmpty = function() {
  return (this.length === 0 || !this.trim());
};



     function RegistrarUsuario(){
    var comprobar = false;
    //Datos proporcionado por el usuario
    js_matricula =$("#matricula_1").val();
    js_nombre =$("#nombre_1").val();
    js_apellido_pa =$("#apellido_pa_1").val();
    js_apellido_ma =$("#apellido_ma_1").val();
    js_carrera = $('#id_carrera').val();

var arreglo = new Array(js_matricula, js_nombre,js_apellido_pa,js_apellido_ma);
for(var i=0; i<arreglo.length; i++){
    if(arreglo[i].isEmpty()){
         comprobar = true;
         break;
    }
}

if(comprobar){
    alert("Por favor, no deje ningun campo sin texto.");
    return;
}

var request = $.ajax({
  url: "Verificacion/Validar_Entrada.php",
  method: "POST",
  data:{ matricula:js_matricula, nombre:js_nombre, apellido_pa:js_apellido_pa, apellido_ma:js_apellido_ma, id_carrera: js_carrera},
  dataType:"jsonp",
  jsonp:"jsoncallback",
  crossDomain: true,
  cache: false
});

request.done(function( data ) {
          if(data.estado=="exito"){
              alert("Muy bien");
          }else{
              alert("Algo inesperado a ocurrido, por favor intentelo más tarde.");
          }
});

request.fail(function( jqXHR, textStatus ) {
alert( "Error en la petición: " + textStatus );
});

return false;
 }   

My .php

    <?php

  header("Content-type: application/json");


    $matricula = $_GET['matricula'];
    $nombre = $_GET['nombre'];
    $apellido_pa = $_GET['apellido_pa'];
    $apellido_ma = $_GET['apellido_ma'];
    $id_carrera = $_GET['id_carrera'];
    $id_carrera =  (!empty($id_carrera))  ?  $id_carrera  : NULL ;



    $datos = array();

    $nombre = trim($nombre , " ");
    $apellido_pa = trim($apellido_pa , " ");
    $apellido_ma = trim($apellido_ma , " ");

    //Deja solo un espacio en blanco entre palabras
    $nombre  = preg_replace( "([ ]+)"," ",$nombre);
    $apellido_pa  = preg_replace( "([ ]+)"," ",$apellido_pa);
    $apellido_ma  = preg_replace( "([ ]+)"," ",$apellido_ma);



    include_once('Conexion/Abrir_Conexion.php');

    $sql = "INSERT INTO alumno (matricula, nombre, apellido_pa, apellido_ma, id_carrera) 
             VALUES 
            (?, ?, ?, ?, ?)";

    $sentencia=$conexion->prepare($sql);
    $sentencia->bind_param("isssi", $matricula, $nombre, $apellido_pa, $apellido_ma, $id_carrera);

    if($sentencia->execute()){
        $datos["estado"] = "exito"; 
    }else{
        $datos["estado"] = "error";
    }

    $sentencia->close();
    $conexion->close();

    $resultadoJson = json_encode($datos);
    echo $_GET['jsoncallback'] . '(' . $resultadoJson . ');';

Friends make changes that you suggested to me but now it does not send me the error, I do not know if it is the dataType, because even then it does not send me the alert (that if it is right or wrong or the error throws me); just insert records reload the page and again again. What's happening ???

    
asked by Diegos Sánchez 16.07.2018 в 07:06
source

2 answers

1

The problem is not so much the divergence between GET / POST. If I remember correctly, I have tried to send by POST and read by GET and there was no problem in showing the data. Even so, it is convenient to be coherent: if POST is POST in everything.

The main problem is that, since you are using JSONP in the answer, your url has to end like this: &callback=? , otherwise it will not work.

Doing a test on my server, I've done it by doing the following:

In Javascript:

  • Removing jsonp:"jsoncallback",

In PHP:

  • Using GET (even if the request from the client is POST ), and putting the key callback in GET . If I put something other than callback it does not work.

Here I leave the code. I will also put preventDefault to prevent the page from refreshing and the entire code block within function to make sure that the DOM is ready before launching the request.

The code is adapted to the jQuery recommendations: type is for old versions of jQuery, it is recommended to use method instead.

Also success is obsolete from jQuery 3, it is recommended to use done and also implement at least fail to inform when the request fails and not leave the user waiting believing that the request is being processed. jQuery I recommend creating the Ajax request in a variable and then adding the functions done , fail and, eventalmente always , complete . This is a way to take advantage of the structure similar to Promises that jQuery implements in Ajax requests.

For more details on everything said above you can check the documentation .

$(function() {
    $("#enviar").click(function(e) {
        e.preventDefault();
        RegistrarUsuario();
    });

    String.prototype.isEmpty = function() {
        return (this.length === 0 || !this.trim());
    };

    function RegistrarUsuario() {
        var request=$.ajax({
                        url: "Verificacion/Validar_Entrada.php",
                        method: "POST",
                        data:{ matricula:js_matricula, nombre:js_nombre, apellido_pa:js_apellido_pa, apellido_ma:js_apellido_ma, id_carrera: js_carrera},
                        dataType:"jsonp",
                        crossDomain: true,
                        cache: false
        });

        request.done(function( data ) {
                        if(data.estado=="exito"){
                            alert("Muy bien");
                        }else{
                            alert("Algo inesperado a ocurrido, por favor intentelo más tarde.");
                        }
        });

        request.fail(function( jqXHR, textStatus ) {
          alert( "Error en la petición: " + textStatus );
        });

        /*Opcional: Lo puedes usar para mostrar algo cuando termine la petición*/
        request.complete(function() {
                console.log("fin");
        });

        }
});

I do not know exactly what the return false; means at the end of the code. The truth is that with this structure you can implement a request.completed (see the documentation in the link above, this part is explained at the end) and put there what you want, when the cycle of the request is over.

PHP

The PHP code is correct. You just have to put callback in the GET and it might be better to put a header to indicate the type of content and the coding, before printing the output:

//... todo lo anterior igual
header("Content-type: application/json; charset=utf-8");
echo $_GET['callback'] . '(' . $resultadoJson . ');';
  

NOTE:

     

Requests using JSONP are usually used when there are origins   different (from one domain data is requested to another different domain).   If your request is within the same domain maybe the simplest is   make a normal request, without using callbacks .

    
answered by 16.07.2018 / 17:06
source
0

this is your error pana you can not send parameters by post and then receive them with get or you decide by post or by get , I recommend post will always be safer what to get

$.ajax({
              type: "POST", //en mi la mayoria de vecez uso post 
              url: "Verificacion/Validar_Entrada.php",
              data:{ matricula:js_matricula, nombre:js_nombre, apellido_pa:js_apellido_pa, apellido_ma:js_apellido_ma, id_carrera: js_carrera},
              dataType:"jsonp",
              jsonp:"jsoncallback",
              crossDomain: true,
              cache: false,
              success: function(data){
                if(data.estado=="exito"){
                    alert("Muy bien");
                }else{
                    alert("Algo inesperado a ocurrido, por favor intentelo más tarde.");
                }
              }
});
//Este return es de mi funcion
      return false;

ASI would be your php

 $matricula = $_POST['matricula'];
        $nombre = $_POST['nombre'];
        $apellido_pa = $_POST['apellido_pa'];
        $apellido_ma = $_POST['apellido_ma'];
        $id_carrera = $_POST['id_carrera'];

        $id_carrera =  (!empty($id_carrera))  ?  $id_carrera  : NULL ;


    $datos = array();

        $nombre = trim($nombre , " ");
        $apellido_pa = trim($apellido_pa , " ");
        $apellido_ma = trim($apellido_ma , " ");

        //Deja solo un espacio en blanco entre palabras
        $nombre  = preg_replace( "([ ]+)"," ",$nombre);
        $apellido_pa  = preg_replace( "([ ]+)"," ",$apellido_pa);
        $apellido_ma  = preg_replace( "([ ]+)"," ",$apellido_ma);

    include_once('Conexion/Abrir_Conexion.php');

        $sql = "INSERT INTO alumno (matricula, nombre, apellido_pa, apellido_ma, id_carrera) 
                 VALUES 
                (?, ?, ?, ?, ?)";

        $sentencia=$conexion->prepare($sql);
        $sentencia->bind_param("isssi", $matricula, $nombre, $apellido_pa, $apellido_ma, $id_carrera);

        if($sentencia->execute()){


            $datos["estado"] = "exito";
        }else{
            $datos["estado"] = "error";
        }

        $sentencia->close();
        $conexion->close();
        $resultadoJson = json_encode($datos);
        echo $_GET['jsoncallback'] . '(' . $resultadoJson . ');';
    
answered by 16.07.2018 в 15:18