[英]Updating database using AJAX form
I have a file, form.php
, that has a small form for searching the database for people by first and last name. 我有一个文件form.php
,该文件有一个小形式,用于按名字和姓氏搜索数据库中的人。 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. 该表单使用JavaScript函数通过AJAX将变量发送到search_name.php
,并将mydatabase
查询的信息作为表单中的值发送。
I want to be able to update the information on the form in the #result
element with the results from the search. 我希望能够使用搜索结果来更新#result
元素中表单上的信息。
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. 我尝试做一个小的示例,该示例没有通过AJAX返回表单,但它确实起作用,但是由于某种原因,我无法在较大的项目中这样做。
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. 我一直在寻找示例和信息,但是我是AJAX和PHP的新手,无法弄清楚为什么会这样。
form.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 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.";
}
?>
As Timmy mentioned there is no submit value being posted (that only happens automatically if the post was triggered via a form). 正如Timmy提到的,没有要提交的提交值(只有通过表单触发了该提交值时,该值才会自动发生)。 Also, you are trying to grab $_POST['first_name'] when you're sending 'firstname' (same goes for last_name vs lastname). 另外,您在发送“名字”时尝试获取$ _POST ['first_name'](last_name与lastname相同)。
It's important to use some sort of developer tool when you are working with JavaScript / AJAX. 在使用JavaScript / AJAX时,使用某种开发人员工具非常重要。 I personally use Chrome Developer Tools (Press F12 in Chrome https://developers.google.com/chrome-developer-tools/ ). 我个人使用Chrome开发者工具(在Chrome浏览器中按F12 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脚本重写为:
<?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. 我还更新了您的MySQL查询,以使用LIKE字符串比较功能,该功能更适合搜索。 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 . 有关字符串比较功能的更多信息,请访问: 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. 复制和粘贴代码现在应该可以解决您的问题。
Your javascript here:- 您的JavaScript在这里:-
var vars = "firstname="+fn+"&lastname="+ln;
is not including "submit" which your PHP script requires to search the database, here:- 不包括您的PHP脚本搜索数据库所需的“提交”,这里:
if(isset($_POST['submit'])){
So if you just add +"&submit=true"
to the end of your vars variable, it should fix the given problem. 因此,如果仅在vars变量的末尾添加+"&submit=true"
,它应该可以解决给定的问题。
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 =) 当然,当您的PHP脚本查找最初未发送的许多其他变量时,您会看到很多未定义的索引警告=)
Hope this is of some help! 希望这个对你有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.