使用超链接

时间:2015-11-25 13:01:06

标签: php html

我试图通过回显输入字段来创建编辑表单。问题是我的代码没有检测到我在编辑表单中更改的输入值。当我点击更新超链接时,我得到了#34;未定义索引"在POST变量。我想知道,解决这个问题的正确方法是什么?

If I click the discette image it will do the editLanguage.php

edit.html

<?php
  // connect to the database
  include('Connections/connect.php');

  $studentId = ($_SESSION['student']);

  if ($result = $mysqli->query("SELECT * FROM tbllanguage WHERE studentId=$studentId"))
  {
    if ($result->num_rows != 0) {

      // display data in table

      echo "<p>";              
      echo "<div id='body'>";
      echo "<div id='content'>";
      echo "<table align='center' border='0' width='400'>";
      echo "<tr> <th>Language</th> <th>Spoken</th>  <th>Writen</th> <th></th><th></th><th></th></tr>";

      while($row = mysqli_fetch_array($result)) {

        // echo out the contents of each row into a table
        echo "<form id=\"Form".$row[0]."\" accept-charset='UTF-8'>";//DO THIS: ADD THIS
        echo "<input type='hidden' name='id' id='".$row[0]."'>";//DO THIS: ADD THIS
        //echo "<input type='text' name='id' value='".$row[0]."'>";   

        echo "<tr>";
        echo "<td>";
        echo '<select id="language" name="language" style="width:200px;float:left;" class="form-control">
                <option value='.$row[1].'> '.$row[1].'</option>
                <option value="Malay">Malay</option>
                <option value="English">English</option>
                <option value="Chinese">Chinese</option>
                <option value="Tamil">Tamil</option>
              </select>';
        echo "</td>";
        echo "<td>";
        echo '<select id="spoken" name="spoken" style="width:200px;float:left;" class="form-control">
                <option value='. $row[2] .'>'. $row[2] .'</option>
                <option value="Very Good">Very Good</option>
                <option value="Good">Good</option>
                <option value="Moderate">Moderate</option>
                <option value="Bad">Bad</option>
                <option value="Very Bad">Very Bad</option>
              </select>';
        echo "</td>";
        echo "<td>";
        echo '<select name="writen" id="writen" style="width:200px;float:left;" class="form-control">
                <option value='. $row[3] .'>'. $row[3] .'</option>
                <option value="Very Good">Very Good</option>
                <option value="Good">Good</option>
                <option value="Moderate">Moderate</option>
                <option value="Bad">Bad</option>
                <option value="Very Bad">Very Bad</option>
              </select>';
        echo "</td>";
        echo '<td>'. "&nbsp;" .'</td>';
        echo "<td>";
        echo '<a href="deleteLanguage.php?id=' . $row[0] . '"><img src="image/delete.png" width="16" height="16" /></a>';
        echo "</td>";
        echo '<td>'. "&nbsp;" .'</td>';
        echo '<td>'. "&nbsp;" .'</td>';
        echo '<td>'. "&nbsp;" .'</td>';
        echo "<td>";
        echo '<a href="#" id="'.$row[0].'" onclick="editData(this.id)"><img src="image/save.png" width="16" height="16" /></a>';
        echo "</td>";
        echo "</tr>";
      }

      echo "</table>";
      echo "</div>";
      echo "</div>";
      echo "</center>";
      echo "<p></p>";
      echo '<input type="submit" value="Cancel" id="btnCancel" name="cancel" class="btn btn-danger" />';
      echo "</form>";

    }
  }

  // close database connection
  $mysqli->close();

?>

editLanguage.php

<?php
  error_reporting(E_ALL);
  // connect to the database
  include('Connections/connect.php');

  function renderForm($id='')
    if (isset($_POST['id']) && is_numeric($_POST['id']))
    {  
      $id = $_POST['id'];
      $language = $_POST['language'];
      $spoken = $_POST['spoken'];
      $writen = $_POST['writen'];

      // update record from database
      if ($stmt = $mysqli->prepare("UPDATE tbllanguage SET language = ?, spoken = ?, writen = ? WHERE languageId=?"))
      {
        $stmt->bind_param("sssi",$language,$spoken,$writen, $id);  
        $stmt->execute();
        $stmt->close();
        echo "Success";//return this string to js if form success
      } else {
         echo "ERROR: could not prepare SQL statement.";
      } 
    }

  $mysqli->close();

?>

的Javascript

<script>
function editData(id) {
    var url = "editLanguage.php";
    var xhttp = new XMLHttpRequest();
    var formId = "Form"+id;
    if (confirm("Confirm update data?")) {
        var form = document.getElementById(formId);
        var formData = new FormData(form);
        xhttp.onreadystatechange = function() {
           if (xhttp.readyState == 4 && xhttp.status == 200) {
               if (xhttp.responseText == "Success"){
                   //alert("Updated successfully");
                   //location.reload(true);
                   window.document.write(xhttp.responseText);
               }else{
                   //alert("Something went wrong");
                   //location.reload(true);  
                     window.document.write(xhttp.responseText);                        
               }   
           }                       
       }

        xhttp.open("POST",url,true);
        xhttp.send(formData);
    }else{
        alert("Cancelled, no changes made.");
        return false;
    }
}
</script>

1 个答案:

答案 0 :(得分:0)

<强> edit.html

<?php
    //DO THIS: REMOVE THIS-> <form id='frmlanguage' action='editLanguage.php' method='post' accept- charset='UTF-8'>


    //.....your own code until.....

     while($row = mysqli_fetch_array($result)) {

   // echo out the contents of each row into a table
    echo "<form id=\"Form".$row[0]."\" accept-charset='UTF-8'>";//DO THIS: ADD THIS

    echo "<input type='hidden' name='id' value='".$row[0]."'>"; 
    echo "<tr>";
    echo "<td>";
    echo '<select id="language" name="language"  style="width:200px;float:left;" class="form-control">
            <option value='.$row[1].'> '.$row[1].'</option>
            <option value="Malay">Malay</option>
            <option value="English">English</option>
          </select>';

    //your own code until......
    echo '<a href="#" id="'.$row[0].'" onclick="editData(this.id)"><img src="image/save.png" width="16" height="16" /></a>';//DO THIS <- Assign onclick event

    //rest of your code until....
    echo '<input type="submit" value="Cancel" id="btnCancel" name="cancel" class="btn btn-danger" />';  
    echo "</form>";//DO THIS <- close form tag.
  }
}
  // close database connection
  $mysqli->close();
?>

<强>的JavaScript

//this can be placed anywhere in edit.html, preferably at the <head> section
//but place it outside <?php /*don't put here*/ ?> tag. or you can use a link to it, even better.
<script>
function editData(id) {
    var url = "editLanguage.php";
    var xhttp = new XMLHttpRequest();
    var formId = "Form"+id;
    if (confirm("Confirm update data?")) {
    var form = document.getElementById(formId);
    var formData = new FormData(form);
    xhttp.onreadystatechange = function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                        if (xhttp.responseText == "Success"){
                            alert("Updated successfully");
                            location.reload(true);
                        }else{
                            alert("Something went wrong");
                            location.reload(true);                          
                        }   
                    }                       
                }

            xhttp.open("POST",url,true);
            xhttp.send(formData);
        }else{
            alert("Cancelled, no changes made.");
        return false;
        }
}
</script>

<强> editLanguage.php

//remove unnecessary code, we don't require any other things else here except for validation or argument
<?php
error_reporting(E_ALL);
// connect to the database
include('Connections/connect.php');

if (isset($_POST['id'])// && is_numeric($_POST['id']))
   {  
      $id = $_POST['id'];
      $language = $_POST['language'];
      $spoken = $_POST['spoken'];
      $writen = $_POST['writen'];

      // update record from database
      if ($stmt = $mysqli->prepare("UPDATE tbllanguage SET language = ?, spoken = ?, writen = ? WHERE languageId=?"))
      {
         //$stmt->bind_param("sssi",$language,$spoken,$writen, $id);  
         $stmt->execute(array($language,$spoken,$written,$id));
         $stmt->close();
         echo "Success";//return this string to js if form success
      } else {
         echo "ERROR: could not prepare SQL statement.";
      } 
  }
$mysqli->close();
?>

这里发生了什么?

<强> 1。我们将表单ID分配给我们返回的每一行结果。

//echo "<form id=\"Form".$row[0]."\" accept-charset='UTF-8'>"; Form+id
//return Form1, Form2, Form3 and so on, id generated using the result
//from the query. It will look like:
    <form id="Form1" accept-charset="UTF-8">

<强> 2。我们分配一个onclick事件来触发js函数。

我们触发的函数是editData,如下所示,并沿着这个超链接id传递,href =&#34;#&#34;什么都不返回,为了这个例子,我们只是在点击时不想要这个链接,将页面重定向到其他任何地方。

echo '<a href="#" id="'.$row[0].'" onclick="editData(this.id)"><img src="image/save.png" width="16" height="16" /></a>';

看起来像:

<a href="#" id="1" onclick="editData(this.id)"><img src="image/save.png" width="16" height="16"></a>

当Javascript函数被触发时,我们得到超链接的id传递,因为我们已经设置,超链接的数字id与我们创建的形式相同,因此我们创建了对表单的引用。

    var url = "editlanguage.php";//send the form to this page

    var formId = "Form"+id;// return string Form1, Form2 or so on.

    if (confirm("Confirm update data?"))....//just a confirmation box

    var form = document.getElementById(formId);//get Form byFormId set earlier as var formId

    xhttp.onreadystatechange = function() {......//the magical moment, read more about it.


if (xhttp.responseText == "Success"){//if string success is returned by editLanguage
                            alert("Updated successfully");
                            location.reload(true);//refresh page
                        }else{
                            alert("Something went wrong");
                            location.reload(true);  //refresh page                      

alert("Cancelled, no changes made.");....//if cancel is click.

第3。 editLanguage.php中的查询将使用POST var查询结果,我们只想返回一个字符串&#34;成功&#34;因为我们正在倾听&#34;从Javascript到此字符串,以提示如上所述的警报。

希望这有帮助。