2014-01-22 98 views
0

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

我希望能够使用搜索结果更新#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."; 


} 

?> 
+0

**危险**:您正在使用[an **过时的**数据库API](http://stackoverflow.com/q/12859942/19068)并应使用[现代替换](http:// php.net/manual/en/mysqlinfo.api.choosing.php)。你也很容易受到[SQL注入攻击](http:// bobby-tables。/ **)一个现代的API会让你更容易[防守](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)。 – Quentin

回答

0

您的JavaScript这里: -

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

不包括 “提交”,你的PHP脚本需要搜索数据基地,在这里: -

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

所以,如果你只需要添加+"&submit=true"您瓦尔变量的末尾,它应该可以解决给定的问题。

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

当然,你会看到很多未定义指数的警告当成你的PHP脚本查找很多其他变数最初未发送=)

希望这是一些帮助!

+0

谢谢这确实有帮助,虽然我有很多变数。我决定不使用这种方法。 – user2687915

1

正如Timmy所说,没有提交任何提交值(只有在通过表单触发后才会自动发生)。另外,当你发送'firstname'时,你试图抓住$ _POST ['first_name'](last_name和lastname相同)。

当您使用JavaScript/AJAX时,使用某种开发人员工具很重要。我个人使用Chrome开发者工具(按Chrome中的F12 https://developers.google.com/chrome-developer-tools/)。这会告诉你什么请求/响应实际上是什么样子,这样你就可以找出你的问题。根据你的前面到底是什么做的,我很快就改写了您发布的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。现在,代码的复制和粘贴应该可以解决您的问题。