使用AJAX表单更新数据库

问题描述:

I have a file, form.php, that has a small form for searching the database for people by first and last name. The form uses a JavaScript function to send variables to search_name.php through AJAX and information queried from mydatabase as values in a form.

I want to be able to update the information on the form in the #result element with the results from the search.

I tried doing a small example that did no have the form returned through AJAX and it worked but for some reason I am not able to do it in my bigger project.

Can anyone please help. I have looked for examples and information but I'm new to AJAX and PHP and can't figure out why this is happening.

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 
";
            document.getElementById("first_name").focus();
        }       
        if (ln==null || ln=="" ){
            errorMsg +="Enter Last Name 
";
            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.";


}

?>

Your javascript here:-

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

is not including "submit" which your PHP script requires to search the database, here:-

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

So if you just add +"&submit=true" to the end of your vars variable, it should fix the given problem.

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

Of course, you will see a lot of Undefined index warnings as your PHP script looks for lots of other variables that aren't sent initially =)

Hope this is of some help!

As Timmy mentioned there is no submit value being posted (that only happens automatically if the post was triggered via a form). Also, you are trying to grab $_POST['first_name'] when you're sending 'firstname' (same goes for last_name vs lastname).

It's important to use some sort of developer tool when you are working with JavaScript / AJAX. I personally use Chrome Developer Tools (Press F12 in Chrome https://developers.google.com/chrome-developer-tools/). This will show you what the request / response actually looks like so you can figure out what your issues are. Based on what your front end it doing, I quickly rewrote the PHP script you are posting to:

<?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.";
}

?>

I fixed the bad variable names and commented out the ones that are not being sent over at the moment. I also updated your MySQL query to use the LIKE string comparison function which is much better for searching. This way if someone doesn't know the last name, or only a portion, they can still finish the lookup. More on string comparison functions here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html. A copy and paste of the code should solve your problems for now.