Ajax和MySql插入,检查和检索

时间:2012-09-05 19:46:20

标签: javascript php jquery mysql ajax

我有两个数据库表,访客列表和出勤

在一个HTML页面上,我有一个window.onload脚本,我想通过AJAX检查guestlist。如果url查询中的firstname和lastname出现在guestlist表中,则加载该页面。如果没有,请加载错误消息。

正确加载页面后,firstname和lastname预先填充在两个输入字段中。用户完成表单的其余部分并单击“提交”,将其名字和姓氏插入到考勤表中。

如果firstname和lastname已出现在考勤表中,请加载错误消息。如果出勤表中没有出现名字和姓氏,请将表格信息提交到出勤表。

说到Ajax,我并不是一个明亮的灯泡。这是我目前的代码:

HTML

<body>
<div id="formDiv">
<form id="partyForm" name="party" action="party_insert" method="post">
<h1>Welcome to The Party</h1>
    <input name="first_name" id="firstname" class="input" type="text" maxlength="99" placeholder="First Name"><br/>
    <input name="last_name" id="lastname" class="input" type="text" maxlength="99" placeholder="Last Name"><br/>
    <input name="costume" id="costume" class="input" type="text" maxlength="999" placeholder="What are you supposed to be?"><br/>
    <div id="buttonDiv">
        <a class="button" id="submit" style="cursor:pointer;">SUBMIT</a>
    </div>
</form>
</div>

<script>
window.onload = function () {
    var fname_init = decodeURIComponent(getUrlVars()["fname"]);
    var lname_init = decodeURIComponent(getUrlVars()["lname"]);

    if(fname_init !== "undefined" && lname_init !== "undefined"){
        var newString = 'fname='+encodeURIComponent(fname_init)+'&lname='+encodeURIComponent(lname_init);
        $.ajax({
            type: "GET",
            url: "guestList.php",
            data: newString,
            success: function(){
                alert("ON THE LIST");
                $('#firstname').val(fname_init);
                $('#lastname').val(lname_init);
            },
            error: function(){
                alert("NOT ON THE LIST");
                window.location = 'error1.html?fname='+encodeURIComponent(fname_init)+'lname='+encodeURIComponent(lname_init);
            }
        })
    }
}

$("#submit").click(function() {
    validate();
});

function submit(){
    var fname = $("#firstname").val();
    var lname = $("#lastname").val();
    var cost = $("#costume").val();
    var dataString = 'fname='+encodeURIComponent(fname)+'&lname='+encodeURIComponent(lname)+'&cost='+encodeURIComponent(cost);
    $.ajax({  
        type: "POST",  
        url: "partyEntry.php",  
        data: dataString,  
        success: function() {  
            alert("ENJOY THE PARTY");
            clearForms();
        }
    });
}

function validate(){
    if ($("#firstname").val() == ""){
        alert("Please Enter your First Name");
    } else {
        if ($("#lastname").val() == ""){
            alert("Please Enter your Last Name");
        }else{
            if ($("#costume").val() == ""){
                alert("You have to have a costume to be eligible for this raffle");
            }else{
                submit();
            }
        }
    }
}

function clearForms() {
    $('#partyForm')[0].reset();

}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

</script>
</body>

guestList.php

<?php

    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "party";

    $link = mysql_connect($host, $user, $password);
    mysql_select_db($database);

    //SURVEY INFORMATION
    $fname = mysql_real_escape_string($_REQUEST['fname']);
    $lname = mysql_real_escape_string($_REQUEST['lname']);

    $checkClient  = "SELECT * FROM guestlist WHERE first_name = ".$fname." AND last_name = ".$lname;
    mysql_query($checkClient) or die(mysql_error());

    mysql_close($link);

?>

partyEntry.php

<?php

    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "party";

    $link = mysql_connect($host, $user, $password);
    mysql_select_db($database);

    //SURVEY INFORMATION
    $fname = mysql_real_escape_string($_REQUEST['fname']);
    $lname = mysql_real_escape_string($_REQUEST['lname']);
    $cost = mysql_real_escape_string($_REQUEST['cost']);

    $addClient  = "INSERT INTO attendance (first_name, last_name, costume) VALUES ('$fname','$lname', '$cost')";
    mysql_query($addClient) or die(mysql_error());

    mysql_close($link);

?>

我得到的错误是,即使名单不在嘉宾列表中,它仍然会显示它们在列表中。所以我必须在对guestlist.php的Ajax调用中做错事,但我不知道是什么。我也遇到了编写ajax调用脚本以检查访客是否已被放入考勤表的问题。

3 个答案:

答案 0 :(得分:1)

根据REST原则,使用HTTP 200响应POST请求意味着资源已成功创建。您可以使用HTTP 400进行响应,并以text / html / json / xml格式提供有关错误的详细信息。

尝试这样做,

添加以下代码

$query = mysql_query($addClient) or die(mysql_error());

if(mysql_num_rows($query) > 0)
{
     header('HTTP/1.1 500 Internal Server Error');
     echo 'this is an error message';
}

答案 1 :(得分:1)

就像我在评论中说的那样,你必须从guestList.php返回一个值,这样的事情应该有效:

$checkClient  = "SELECT * FROM guestlist 
                 WHERE first_name = ".$fname." AND 
                       last_name = ".$lname;
$result = mysql_query($checkClient);
$count = mysql_num_rows($result);
mysql_close($link);
// output 1 or 0 stating if the user is on the list or not
echo ($count ? 1 : 0);
exit();

然后在你的ajax回调中你会做一个检查:

success:function(e) {
   alert((e == 1 ? "User is on list" : "User isn't on list"));

答案 2 :(得分:0)

至少在尝试执行无效查询时,php脚本永远不会抛出错误。执行查询没有任何错误,因为它格式正确,因为你没有从数据库中获取行,所以不会抛出错误。