使用AJAX表单更新数据库

时间:2014-01-22 23:49:11

标签: javascript php jquery mysql ajax

我有一个文件form.php,它有一个小表单,用于按名字和姓氏搜索数据库。该表单使用JavaScript函数通过AJAX将变量发送到search_name.php,并将mydatabase中查询的信息作为表单中的值发送。

我希望能够使用搜索结果更新#result元素中表单上的信息。

我尝试做一个小例子,没有通过AJAX返回的表单,但是它有效,但由于某种原因,我无法在我的大项目中做到这一点。

任何人都可以帮忙。我已经查找了示例和信息,但我是AJAX和PHP的新手,无法弄清楚为什么会这样。

form.php的

<script language="JavaScript" type="text/javascript">
    function ajax_post(){
        var fn = document.getElementById("first_name").value;
        var ln = document.getElementById("last_name").value;
        var errorMsg ="";
        if (fn==null || fn=="" ){
            errorMsg +="Enter First Name \n";
            document.getElementById("first_name").focus();
        }       
        if (ln==null || ln=="" ){
            errorMsg +="Enter Last Name \n";
            document.getElementById("last_name").focus();
        }       
        if(errorMsg != ""){
            alert(errorMsg);
            document.getElementById("first_name").focus();
            return false;       
        }else{ 
            // Create our XMLHttpRequest object
            var hr = new XMLHttpRequest();
            // Create some variables we need to send to our PHP file
            var url = "search_name.php";        
            var vars = "firstname="+fn+"&lastname="+ln;
            hr.open("POST", url, true);
            // Set content type header information for sending url encoded variables in the request
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // Access the onreadystatechange event for the XMLHttpRequest object
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var return_data = hr.responseText;
                    document.getElementById("result").innerHTML = return_data;
                }
            }
            // Send the data to PHP now... and wait for response to update the status div
            hr.send(vars); // Actually execute the request
            document.getElementById("result").innerHTML = "processing...";        
        }
    }
</script>
</head>
<body>
    <div class="left" id="search">
        First Name: <input id="first_name" name="first_name" type="text" /> 
        <br /><br />
        Last Name: <input id="last_name" name="last_name" type="text" />
        <br /><br />
        <input name="myBtn" type="submit" value="Search" onClick="javascript:ajax_post();return">
        <br /><br />
    </div>
    <div id="result"></div>

search_name.php

<?php $form_profile = '<form method="POST" action=""><table width="450px"><tr><td><label for="firstname" >First Name: </label></td><td><input  type="text" id="first_name" name="first_name" maxlength="50" size="30" value="'.$first_name.'"/></td></tr><tr><td><label for="lastname" >Last Name: </label></td><td><input  type="text" id="last_name" name="last_name" maxlength="50" size="30" value="'.$last_name.'"/></td></tr><tr><td><label for="headline">Headline</label></td><td><input  type="text" id= "headline" name="headline" maxlength="50" size="30" value="'.$profile_headline.'"/></td></tr></table><input type="submit" id="submit" name="submit" value="Save and Update"></form>'; ?>

<?php
//check if form has been submitted
if(isset($_POST['submit'])){

    $first_name= $_POST['first_name'];
    $last_name= $_POST['last_name'];
    $headline= $_POST['headline'];
    $summary= $_POST['summary'];


    $title_array= $_POST['title'];
    $company_array= $_POST['company'];
    $start_month_array= $_POST['start_month'];
    $start_year_array= $_POST['start_year'];
    $end_month_array= $_POST['end_month'];
    $end_year_array= $_POST['end_year'];

    if($first_name && $last_name){
        //connect to server
        $link = mysql_connect("localhost", "root", "########");

        if($link){
            mysql_select_db("mydatabase",$link);
        }


        //check if person exists
        $exists = mysql_query("SELECT * FROM profile WHERE firstname = '$first_name' AND lastname = '$last_name'") or die ("The query could not be complete.");
            if(mysql_num_rows($exists) != 0){
                //update
                mysql_query("UPDATE profile SET  headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
                echo "Success!!";

}else echo "That alumni is not in the database";
}else echo "You must provide a first and last name.";


}

?>

2 个答案:

答案 0 :(得分:1)

正如蒂米提到的那样,没有提交任何提交值(只有在通过表单触发帖子时才会自动发生)。此外,当你发送'firstname'时,你试图抓住$ _POST ['first_name'](对于last_name和lastname也一样)。

在使用JavaScript / AJAX时,使用某种开发人员工具非常重要。我个人使用Chrome开发者工具(在Chrome https://developers.google.com/chrome-developer-tools/中按F12)。这将向您显示请求/响应的实际情况,以便您了解问题所在。根据你的前端做了什么,我很快重写了你发布的PHP脚本:

<?php
//check if form has been submitted
if(isset($_POST['firstname']) || isset($_POST['lastname'])){

    $first_name= $_POST['firstname'];
    $last_name= $_POST['lastname'];

    /*
    $headline= $_POST['headline'];
    $summary= $_POST['summary'];
    $title_array= $_POST['title'];
    $company_array= $_POST['company'];
    $start_month_array= $_POST['start_month'];
    $start_year_array= $_POST['start_year'];
    $end_month_array= $_POST['end_month'];
    $end_year_array= $_POST['end_year'];
     */


    //connect to server
    $link = mysql_connect("localhost", "root", "########");

    if($link){
        mysql_select_db("mydatabase",$link);
    }


    //check if person exists
    $exists = mysql_query("SELECT * FROM profile WHERE firstname  LIKE $first_name.'%' AND lastname  LIKE $last_name.'%'") or die ("The query could not be completed.");
    if(mysql_num_rows($exists) != 0){
        //update
        //mysql_query("UPDATE profile SET  headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");

        echo "Success!!";

    } else {
        echo "That alumni is not in the database";
    }
} else {
    echo "You must provide a first and last name.";
}

?>

我修复了错误的变量名称并注释掉了那些目前尚未发送的变量名称。我还更新了你的MySQL查询以使用LIKE字符串比较函数,这对于搜索更好。这样,如果有人不知道姓氏或只知道一部分,他们仍然可以完成查找。有关字符串比较函数的更多信息,请访问:http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html。代码的复制和粘贴现在可以解决您的问题。

答案 1 :(得分:0)

您的javascript在这里: -

    var vars = "firstname="+fn+"&lastname="+ln;

不包括您的PHP脚本搜索数据库所需的“提交”,此处: -

if(isset($_POST['submit'])){

因此,如果您只是将+"&submit=true"添加到vars变量的末尾,则应解决给定的问题。

var vars = "firstname="+fn+"&lastname="+ln+"&submit=true";

当然,您会看到许多未定义的索引警告,因为您的PHP脚本会查找最初未发送的许多其他变量=)

希望这有一些帮助!