使用ajax在div中提交表单,在div中返回php而不刷新

时间:2012-12-21 15:48:46

标签: php jquery ajax html

我有一个索引页面,顶部有三个按钮。在单击每个按钮时,php文件将加载到主div中。其中一个按钮加载用户填写并提交的表单。在提交表单时,我需要它不刷新页面并将结果数据加载到表单页面上的div ...而不是主div。

如果我自己加载表单页面(即,不是通过单击按钮,而只是键入表单本身的地址)......一切正常。表单验证有效,它提交时不进行刷新,结果数据将返回到表单上的结果div中。

但是,我加载索引页面并单击按钮以加载表单。表单正确加载,但是当我单击提交它时只刷新页面...这导致表单消失,因为加载它的div最初是隐藏的。此外,表单不验证,也不执行php操作。

同样,表单及其关联php完全可以自己完成。只有在索引页面中加载表单时才会出现此问题。所以我假设这个问题与我将其加载到索引页面上的div中有关。任何帮助将不胜感激。

索引代码:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

</head>
<body>

<div id="header">
<center><h2>OMS Tutoring Database</h2></center>
</div>
<div id="navbar">
<center>
<button class="navbutton" id="buttonview" type="button">View Tutoring Lists</button>
<button class="navbutton" id="buttonadd" type="button">Add Students</button>
<button class="navbutton" id="buttonadmin" type="button">Admin</button>
</center>
<br>
</div>

<div id="content"></div>



<script>
    $(document).ready(function() {
$('#buttonview').click(function(){
    $('#content').load('tutoring.php', function(){
   });


});
$('#buttonadd').click(function(){
    $('#content').load('addtest.php', function(){
   });

});
$('#buttonadmin').click(function(){
    $('#content').load('admin.php', function(){
   });

});
});
  </script>

</body>
</html>

表单代码

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $("#addstudent").validate({
            debug: false,
            rules: {
                studentid: "required",
                teacher: "required",
                assignment: "required",
                date: "required",
            },
            messages: {
                studentid: "Please enter the student's ID number.",
                teacher: "Please enter your name.",
                assignment: "Please select a tutoring assignment.",
                date: "Please select a day.",
            },                 
            submitHandler: function(form) {

      $.ajax({
          url: 'add.php',
          type: 'POST',
          data: $("#addstudent").serialize(),         
          success: function(data) {
        $("#studentid").val("");
        $('#studentid').focus();
        $("#results").empty();
        $("#results").append(data);
        }
      });

      return false;
   }
});
});
</script>

</head>

<title>OMS Tutoring - Add Student</title>
<body>
Use this form to add students to the tutoring list.
<p>
<div style="float:left;width:100%;margin-bottom:10;">
<div>
<form name="addstudent" id="addstudent" action="" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>

<div><label for="day">Date</label><select name="date" id="date">
<option value="">Please select a day</option>
<option value="mon">Monday <? echo $monday; ?></option>
<option value="tue">Tuesday <? echo $tuesday; ?></option>
<option value="wed">Wednesday <? echo $wednesday; ?></option>
<option value="thu">Thursday <? echo $thursday; ?></option>
<option value="fri">Friday <? echo $friday; ?></option>
</select></div>

<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>

<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>

<input type="submit" name="submit" value="submit">
</fieldset>
</form></div></div>

<div id="results" style="margin-left:4;width:350;"><div>

</body>
</html>

表单处理php代码:

<?php

$mysqli = new mysqli('localhost', 'xxx', 'xxx', 'xxx');


$studentid = $_REQUEST['studentid'];
$day = $_REQUEST['date'];
$assignment = $_REQUEST['assignment'];
$teacher = $_REQUEST['teacher'];

$dayquery = $mysqli->query("SELECT date FROM days WHERE day='$day'");
$dayresult = $dayquery->fetch_array();
$date = array_shift($dayresult);

$timestamp = date('Y-m-d H:i:s'); 

$mysqli->query("INSERT INTO assign (id, assignment, assignteacher, date, timestamp)
VALUES ('$studentid', '$assignment', '$teacher', '$date', '$timestamp')");

$namequery = $mysqli->query("SELECT first, last FROM students WHERE students.id='$studentid'");
$nameresult = $namequery->fetch_array();

echo $nameresult['first'].' '.$nameresult['last'].' successfully added.';

$teacherquery = $mysqli->query("SELECT assignteacher FROM assign WHERE id='$studentid' AND date='$date'");

$rowcount = $teacherquery->num_rows;

if ($rowcount > 1) {
  while ($row = $teacherquery->fetch_array()) {
    $teachernames[] = $row[0];
  }
$teachers = implode(', ', $teachernames);
echo '<br><br>Caution: '.$nameresult['first'].' '.$nameresult['last'].' has already been added by the following teachers: '.$teachers.'. ';
echo 'They may have precedence.';
  }
else {
  }

$alreadyadded = $mysqli->query("SELECT assign.id, students.first, students.last, assign.assignment, assign.assignteacher FROM assign
LEFT JOIN students
ON assign.id=students.id
WHERE assign.date='$date' AND assign.assignteacher='$teacher'
ORDER BY assign.assignment ASC, students.last ASC");

echo '<br><br><br>You already have the following student(s) assigned to tutorials on this day';
echo '<table border="1">';
while ($row = $alreadyadded->fetch_array()) {
  echo '<tr><td>'.$row['id'].'</td><td>'.$row['first'].'</td><td>'.$row['last'].'</td><td>'.$row['assignment'].'</td></tr>';
  }
?>

1 个答案:

答案 0 :(得分:1)

使用load方法将表单加载到页面中时,大多数浏览器会删除<head>标记。

来自jquery website

  

在此过程中,浏览器通常会过滤文档中的元素   例如<html><title><head>元素。结果,元素   由.load()检索可能与文档不完全相同   由浏览器直接检索。

因此,请将您的javascript包含在主页面而不是表单页面中,或者手动将javascript动态添加到主页面。