【发布时间】:2017-11-10 07:53:27
【问题描述】:
我想使用 ajax 获取表单数据,然后将其提交到我的 php 页面,然后将其插入到我的数据库中。成功插入时,我想显示“您已成功注册”,失败时显示“注册失败”,如果您已经是会员,我会显示“已经是会员,请登录”。
由于某种原因,我的 ajax 代码无法按预期工作。它跳到最后一部分(else 语句甚至不关心 if 语句)。我的php代码是正确的。因为我已经单独测试过它并且工作正常。
有人可以为我建议一个解决方案或其他方法来完成此操作记住我不想转到另一个页面。
这是我的 JavaScript/jQuery 代码:
$(document).ready(function){
//Signup Js
$("#Register").click(function(){ //#Register is my submit button id
var action = $("#sp-form").attr('action'); //#sp-form is the register form id.
var spform_data = {
myusername: $("#myusername").val(),
myemail: $("#myemail").val(),
mypassword: $("#mypassword").val() //Getting data from the input forms using their respective id's
}
$.ajax({
type: "POST",
url: action,
data: spform_data,
success: function(outcome)
{
if(outcome == "success"){
$("#sp-form").slideUp('slow', function(){
$("#message_sp").html('<p class="success">You have been registered successfully!</p><p style="color:#1c1c1c;">Redirecting....</p>');
});
}
else if(outcome == "alreadymember") {
$("#modal_signup").css("height","380");
$("#message_sp").html('<p class="error">ERROR: Email match found,Just Sign in.</p>');
}
else if(outcome == "failed"){
$("#modal_signup").css("height","380");
$("#message_sp").html('<p class="error">ERROR: Failed to Register</p>');
}
else{
$("#modal_signup").css("height","380");
$("#message_sp").html('<p class="error">ERROR: Unknown ERROR</p>');
}
}
});
return false;
});
});
这是我的 PHP/MySQLi 代码
<?php
if ($_POST)
{
$host = "localhost";
$user= "root";
$password = " ";
try {
$conn = mysqli_connect($host , $user , $password) or die("unable to connect to Local Host"); //Establishing connection with the server
$sql = mysqli_select_db($conn,'audacity') or die("unable to connect to database"); //selecting a database from the server #after connecting
} catch (Exception $e) {
echo $e->getMessage();
}
$name = mysqli_real_escape_string($conn,$_POST['myusername']);
$mail = mysqli_real_escape_string($conn,$_POST['myemail']);
$pass = mysqli_real_escape_string($conn,$_POST['mypassword']);
// Query of SQL
$Query =mysqli_query($conn,"INSERT INTO registration (Username,Email,Password) VALUES ('$name', '$mail' , '$pass')")) //if successful outcome is true
if($Query ==true){
echo "success";
}
elseif ($Query==false) { #if failed
$sqlbd = "SELECT Email FROM registration WHERE Email='$mail' ";
$result = mysqli_query($conn,$sqlbd);
if(mysqli_num_rows($result)==1){ //possible rsn for failure
echo "alreadymember";
}
else{
echo "failed"; //unknown reason.
}
}
mysqli_close($conn);
?>
问题出在哪里???
【问题讨论】:
-
在成功函数的第一行插入console.log(outcome),看看你的控制台浏览器发生了什么。
-
您的数据库有什么变化吗?
-
No.. 我的数据库没有变化
-
你的问题可能出在你的 php 文件中。页面是否返回任何错误标头的错误消息?
-
问题是你必须使用firebug工具来调试你的php代码。