AJAX完成被快速调用

时间:2017-11-20 19:01:38

标签: jquery ajax

出于某种原因,这段代码:

$.ajax({
    type: "POST",
    url: "assets/PHP/registreer.php",
    data: $('form').serialize(),
    complete: function (data) {
        console.log(data.responseText);
    }
})

返回undefined,我认为这是因为当触发完成时尚未返回responseText。但为什么不等呢?我将如何让它等待。

我尝试过很多不同的事情,包括:

jQuery.ajax response data is undefined

AJAX responseText undefined

Jquery Ajax responseText returns undefined but when i log it as an object it returns the ajax text

编辑:包含PHP文件

<?php
session_start();
$emailPost = $_REQUEST["email"];
$passwordPost = $_REQUEST["password"];
$passwordRetypePost = $_REQUEST["retypepassword"];

$servername = "XXXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXXX";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

if ($passwordPost != $passwordRetypePost) {
    echo "Paswoorden zijn niet hetzelfde!";
} else {
    if (!($stmt = $conn->prepare("SELECT * FROM `Gebruikers` WHERE `Email` = 
?"))) {
        echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
    } else {

$stmt->bind_param("s", $emailPost);
$stmt->execute();
$stmt->bind_result($id, $email, $paswoord, $rol);
$stmt->store_result();

if ($stmt->num_rows > 0) {
    echo "Email bestaat al!";
} else {
    $stmt->close();
    $hash = password_hash($passwordPost, PASSWORD_DEFAULT);
    if (!($stmt = $conn->prepare("INSERT INTO `Gebruikers`(`Email`, `Paswoord`) VALUES (?,'$hash')"))) {
        echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
    }

    $stmt->bind_param("s", $emailPost);
    $stmt->execute();
    echo "Gelukt!";
}
}
}

$mysqli->close();
?>

1 个答案:

答案 0 :(得分:-1)

发现问题! 问题是表单的默认设置没有被阻止。所以它在responseText出现之前调用了刷新。

代码已编辑为:

$("#login").submit(function (event) {
    event.preventDefault();
        $.ajax({
            type: "POST",
            url: "assets/PHP/registreer.php",
            data: $('#login').serialize(),
            complete: function (data) {
                alert(data.responseText);
            }
        })
});