简体   繁体   English

Ajax在这种情况下不起作用,我也不知道为什么

[英]Ajax does not work in this case and I don't know why

I'm trying to receive some data as json from a php file, the php seems to be good and the html too, but te jquery file doesn't do the .done function and I can't find why. 我正在尝试从php文件中接收一些数据作为json,php似乎也不错,而html也不错,但是te jquery文件没有执行.done函数,我找不到原因。 The Jquery version that I use is 3.1.0, and I'm using bootstrap for styles but I think it isn't important. 我使用的Jquery版本是3.1.0,我在使用样式引导程序,但我认为这并不重要。

The HTML file: HTML文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registro Chat</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1>Chat 2.0</h1>
<div class="container col-md- mt-4">
    <form id="formulario">
      <div class="form-group">
        <label for="usuario">Nombre de Usuario</label>
        <input type="text" class="form-control" id="usuario" aria-describedby="emailHelp" placeholder="Introduzca el nombre de usuario">
        <p id="p-usuario"></p>
      </div>
      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Introduzca su email">
        <p id="p-email"></p>
      </div>
      <div class="form-group">
        <label for="contra1">Contraseña</label>
        <input type="password" class="form-control" id="contra1" aria-describedby="emailHelp" placeholder="Introduzca una contraseña">
        <p id="p-contra1"></p>
      </div>
      <div class="form-group">
        <label for="contra2">Repita la Contraseña</label>
        <input type="password" class="form-control" id="contra2" placeholder="Repita su contraseña">
        <p id="p-contra2"></p>
      </div>
      <button type="submit" class="btn btn-success bg-success">Enviar</button>
      <a href="principal.html"><button type="button" class="btn btn-success bg-success">Inicio de Sesión</button></a>
    </form>
</div>  
<script src="//code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="accionregistro.js"></script>
</body>
</html>

The JQuery file: JQuery文件:

$(document).ready(principal);

function principal(){

$('#formulario').submit(runAjax);
}

function runAjax(event){

var enviados = {
    'usuario' : $('#usuario').val(),
    'email' : $('#email').val(),
    'contra1' : $('#contra1').val(),
    'contra2' : $('#contra2').val()
    };

$.ajax({
    type        : 'POST',
    url         : 'backendregistro.php',
    data        : enviados,
    dataType    : 'json',
    encode      : true  
})
.done(function(datos){
    alert();

    if(datos.exito){
            alert();
            $('0#p-usuario').text(datos.mensaje);
    }else{
        if(datos.error.vacio){
                alert(datos.error.vacio);
                //$('#p-usuario').text(datos.error.vacio);
        }
        if(datos.error.usuario){
                $('#p-usuario').text(datos.error.usuario);
        }
        if(datos.error.email){
                $('#p-email').text(datos.error.email);
        }
        if(datos.error.notmatch){
                $('#p-contraseña1').text(datos.error.notmatch);
        }
        }

});
event.preventDefault();
}

PHP file: PHP文件:

<?php  
$error=array();
$datos=array();

if(empty($_POST['usuario'])||empty($_POST['contra1'])||empty($_POST['contra2'])||empty($_POST['email'])){
    $error['vacio']="No puede haber campos en blanco";
}else{
    echo
        $usuario = $_POST['usuario'].
        $email = $_POST['email'].
        $contraseña1 = $_POST['contra1'].
        $contraseña2 = $_POST['contra2'];
}
//definimos la conexion a la base de datos
$mysqli = new mysqli('localhost','chat','chat2019','chat');

//comprobamos si el email ya existe
$mysqli -> query("select * from users where email='".$email."'");
if($mysqli->affected_rows!=0&&!empty($email)){
    $error['email']="Ese email ya está registrado";
} 
//comprobamos que no exista el usuario
$mysqli->query("select * from users where user='".$usuario."'");
if($mysqli->affected_rows!=0 && !empty($usuario)){
    $error['usuario']="Ya existe ese nombre de usuario";
}

//si no hay errores hacemos el insert
if(empty($error)){
    $datos['exito']=true;
    $datos['mensaje']="Usuario registrado correctamente";
    $mysqli->query("insert into users values ('".$usuario."','".$contraseña1."','".$email."')");
}else{
    $datos['exito']=false;
    $datos['error']=$error;
}

echo json_encode($datos);  

?>

When I try to see in the console if every thing is going well, it seems that the json is being sent but then the done function doesn't work. 当我尝试在控制台中查看是否一切正常时,似乎正在发送json,但是完成功能无法正常工作。 I'm soo noob at web programing, I know that probably the way I'm doing is very unsecure, but I only want to know why it doesn't works, thanks you. 我对网络编程不太满意,我知道我的工作方式可能很不安全,但是我只想知道为什么它不起作用,谢谢。

I have solve the problem, missing white spaces before and after the function affected_rows in the php file. 我已经解决了这个问题,在php文件中的函数impact_rows前后缺少空格。 Thanks for the answers. 感谢您的回答。

First of all as per jQuery doc , done callback is similar to success . 首先,按照jQuery文档done回调类似于success So you have to try adding fail() and always() callbacks in order to determine response. 因此,您必须尝试添加fail()always()回调以确定响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM