2014-05-06 138 views
0

我在創建我的網站的登錄部分時遇到問題。這是我的js文件general.js:PHP/JQuery/AJAX - 使用AJAX登錄表格

$(document).ready(function() { 

    $("button#submit").click(function(){ 
       $("div#ack").html("please enter username and password"); 

    alert("hi"); 
    if($("#username").val()==""||$("#password").val()=="") 
     $("div#ack").html("please enter username and password"); 
    else 
     $.post($("#login").attr("action"), 
       $("#login :input").serializeArray(), 
       function(data){ 
        $("div#ack").html(data); 
       }); 
    $("#login").submit(function(){ 
     return false; 
    }); 
}); 
}); 

這裏是PHP文件:auth.php

<?php 
session_start(); 

// Connect to the database 
$con = mysqli_connect('localhost','root','root'); 

// Make sure we connected succesfully 
if(! $con) 
{ 
die('Connection Failed'.mysqli_error()); 
} 

// Grab User submitted information 
$username = mysqli_real_escape_string($_POST["username"]); 
$password = mysqli_real_escape_string(md5($_POST["password"])); 

// Select the database to use 
mysqli_select_db("NDE",$con); 

$result = mysqli_query("SELECT username, password FROM fanusers WHERE username =  $username"); 

$row = mysqli_fetch_array($result); 

if($row["username"]==$username && $row["password"]==$password) 
echo"You are a validated user."; 
else 
echo"Sorry, your credentials are not valid, Please try again."; 

?> 

而且index.html的:

<form id="login" action="auth.php" method="POST" class="ui-body ui-body-a ui-corner-all"> 

    <label for="username">Username:</label> 
    <input type="text" name="username" id="username" value="" placeholder="Username" /> 

    <label for="password">Password:</label> 
    <input type="password" name="password" id="password" value="" placeholder="Password" /> 
    <button id="submit">Login</button> 

    </form> 

我不明白爲什麼它直接進入PHP頁面而沒有通過AJAX ...如果有人能夠幫助我一點,那將會很棒

謝謝!

回答

0

其實你忘了加載jquery那裏。加載並檢查它必須工作,添加小提琴演示檢查Firebug網絡XHR窗口,您將獲得Ajax響應。

FIDDLE DEMO

0

試試這個:

$("button#submit").click(function (e){ 
e.preventDefault(); 
      $("div#ack").html("please enter username and password"); 
...}