简体   繁体   English

如何将表格数据从PHP传递到javascript,以html形式显示它,点击提交按钮

[英]How to pass table data from PHP to javascript to display it in the html form onclick of a submit button

I've a form where i have 4 buttons which are used for "insert, update, delete and retrieve" operations for a table. 我有一个表单,我有4个按钮,用于表的“插入,更新,删除和检索”操作。 I can fill in the fields and click any button and respective operations take place. 我可以填写字段并单击任何按钮并执行相应的操作。 The DB operations takes place in PHP. 数据库操作在PHP中进行。 But when the data is being displayed, it goes to a separate page. 但是当显示数据时,它会转到单独的页面。 I want the table data to be displayed in the same page. 我希望表数据显示在同一页面中。 I know it's possible using javascript or something but I'm pretty new to this coding. 我知道可以使用javascript或其他东西,但我对这个编码很新。 So im getting very confused. 所以我很困惑。 Have been trying for the past 3 days. 过去3天一直在尝试。 Nothing worked out. 什么都没有成功。 If anyone could teach me clearly. 如果有人能教我清楚。

HTML: HTML:

<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="open.php">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html> 

PHP: PHP:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error()) 
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];


if(isset($_POST['insert'])){
        $insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
        if($conn->query($insert) === TRUE) {
        echo ("Input data entered successfully");
        } else {
        echo ("Input data failed to be entered" . $conn->error());
        }
        $conn->close();
} elseif(isset($_POST['update'])) {

        $update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
        mysql_query($update);
        if($conn->query($update) === TRUE) {
        echo ("Data updated successfully");
        } else {
        echo ("Data cant be updated" . $conn->error());
        }
        $conn->close();
} elseif(isset($_POST['delete'])) {
        $id = $_POST['Id'];
        $delete = "delete from ins where Id='".$id."'";
        if($conn->query($delete) === TRUE) {
        echo ("Data deleted successfully");
        } else {
        echo ("Data cant be updated" . $conn->error());
        }
        $conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
  }
 mysqli_free_result($result);
}}
$conn->close();
?>

The easiest way to do this is that you should use ajax for this. 最简单的方法是你应该使用ajax。 On clicking each of the buttons send the action to separate files or methods. 单击每个按钮时,将操作发送到单独的文件或方法。 Retrieve whatever comes depending on the type of which action was submitted and successfully update the page. 根据提交的操作类型检索所有内容并成功更新页面。 For eg: If you are retrieving then on click of retrieve you send it to some page where you retrieve the details and return it to the page and just update it. 例如:如果您正在检索然后单击检索,则将其发送到某个页面,您可以在其中检索详细信息并将其返回到页面并进行更新。 It's pretty easy if you do some google on this. 如果你在谷歌上做这个,这很容易。 Make sure all your button actions go to proper respective page. 确保所有按钮操作都转到相应的相应页面。 Hope this was helpful. 希望这有用。

As you mentioned this is one example here: for retrieving(I expect you know how to call another file using ajax and return values.) 正如您所提到的,这是一个示例:用于检索(我希望您知道如何使用ajax调用另一个文件并返回值。)

$.ajax({
        url: 'retrieve.php',
        type: 'post',
        data: { id: id, name: name, blood_group: blood_group },
        success: function(your_success_variable) { 

Here your_success_variable can be an array or json whatever you wish to send from the other file back just don't forget to return 这里your_success_variable可以是一个数组或json,无论你希望从其他文件发回什么,都不要忘记返回

        $('#blood_group').value(your_success_variable['blood_group]);           
                }
            });

You can do it by using two method. 您可以使用两种方法来完成。 First: Create two file one for display your work another for operation. 第一步:创建两个文件,用于显示您的工作另一个用于操作。 when you submit your form it will go on operation page and when after opration is complete you have to set page location to working page like this. 当您提交表单时,它将进入操作页面,当操作完成后,您必须将页面位置设置为这样的工作页面。 header('location:working page.php'); 标题('location:working page.php');

Second: by using Ajax. 第二:使用Ajax。

When the user clicks a SUBMIT-button, your FORM is submitted to open.php on your server. 当用户单击SUBMIT按钮时,您的FORM将提交到服务器上的open.php。 The browser is then taken to that page; 然后浏览器被带到该页面; displaying the output of your PHP script. 显示PHP脚本的输出。

If you don't want to redirect the user, use AJAX in JavaScript as suggested above. 如果您不想重定向用户,请按照上面的建议在JavaScript中使用AJAX。 There's a nice example at: How to make an AJAX call without jQuery? 有一个很好的例子: 如何在没有jQuery的情况下进行AJAX调用?

The neatest way is to use jQuery, but it's more pedagogical to follow the plain JavaScript example. 最好的方法是使用jQuery,但遵循简单的JavaScript示例更具有教学意义。 Essentially, you change your <input type="submit"> to <input type="button"> , and add onClick="performAction('insert');" 基本上,您将<input type="submit">更改为<input type="button"> ,并添加onClick="performAction('insert');" to each button (with the action string according to each operation). 到每个按钮(根据每个操作使用动作字符串)。 The function performAction(act) is declared in JavaScript in your HTML page, and creates an (asychronous!) AJAX call to your open.php script. 函数performAction(act)在HTML页面的JavaScript中声明,并为open.php脚本创建(asychronous!)AJAX调用。

Right now you're submitting the FORM as POST-data. 现在您将FORM作为POST数据提交。 The AJAX call will have to pass the data as (URL-encoded!) GET-data, so performAction(act) appends the FORM data onto the call to open.php. AJAX调用必须将数据作为(URL编码的!)GET数据传递,因此performAction(act)将FORM数据附加到open.php的调用上。 (I presume it's possible to call AJAX with POST-data, and do all this in a more elegant way, but this will work. Hopefully a nice learning example.) (我认为可以用POST数据调用AJAX,并以更优雅的方式完成所有这些,但这样可行。希望这是一个很好的学习示例。)

function performAction (act) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               alert('Request OK, result was: ' + xmlhttp.responseText);
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }

    var GET_encoded_params = "action=" + act 
        + "&Id=" + encodeURIComponent(document.forms[0].Id.value)
        + "&Name=" + encodeURIComponent(document.forms[0].Name.value)
        + "&BloodGroup=" + encodeURIComponent(document.forms[0].BloodGroup.value);

    xmlhttp.open("GET", "open.php?" + GET_encoded_params, true);
    xmlhttp.send();
}

Note that your PHP script might have to "get" the GET-data slightly different than you're getting the POST-data now, but that should be a minor change. 请注意,您的PHP脚本可能必须“获取”GET数据与您现在获取POST数据略有不同,但这应该是一个小的更改。 You will also need to get the desired action (insert, update, delete, retrieve) from the new action parameter. 您还需要从新的action参数中获取所需的操作 (插入,更新,删除,检索)。

Code was borrowed from How to make an AJAX call without jQuery? 代码是从如何在没有jQuery的情况下进行AJAX调用的? and modified without actually testing. 并且没有实际测试而修改。 Beware of typos :) and have fun! 小心拼写错误:),玩得开心!

retrieve button can be placed in a new form where action will be on the same page or empty right now you have placed in a form where action is open.php so every action is performing on that particular page.This will definitely help you if any error occurs let me know. retrieve button可以放在一个新的表单中,其中操作将在同一页面上或空白,现在您已放置在操作为open.php的表单中,因此每个操作都在该特定页面上执行。如果有任何操作,这肯定会对您有所帮助发生错误让我知道。

else if(isset($_POST['retrieve'])) {
    $id = $_POST['Id'];
    $retrieve = "SELECT * FROM `ins` WHERE `Id` = '".$id."';
    if ($result=mysqli_query($conn,$retrieve))
    {
    while ($row=mysqli_fetch_row($result))
    {?>
    <table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Blood Group</td>
    </tr>
    <tr>
    <td><?php echo $row[0];?></td>
    <td><?php echo$row[1];?></td>
    <td><?php echo$row[2];?></td>
    </tr>
    </table>
     <?php  }
     mysqli_free_result($result);
    }}?>

In your code you are directly printing the echo statement in the while loop.Just use a variable $msg which will store all the contents.So your code will be 在你的代码中,你直接在while循环中打印echo语句。只需使用一个变量$ msg来存储所有内容。所以你的代码将是

<?php
    $msg="";
  $msg.= '<table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Blood Group</td>
    </tr>';

  while ($row=mysqli_fetch_row($result))
    {
   $msg.=' <tr>
    <td>'.$row[0].'</td>
    <td>'.$row[1].'</td>
    <td>'.$row[2].'</td>
    </tr>;'

      }
    $msg.='</table>';
   ?>

After this in your html just echo the variable $msg so your html code will be 在你的html之后只需回显变量$ msg,这样你的html代码就可以了

<body>
<h1></h1>
<form>...</form>
<?php echo $msg;?>
</body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 PHP 数组作为参数从 onClick HTML 按钮传递给 Z686155AF75A60A0F36E9D80C1F7? - How to pass a PHP array as parameter from onClick HTML button to JavaScript? 如何在不使用数据库的情况下在html页面中单击提交按钮显示表单数据 - How to display form data onclick of submit button in html page without using Database 我想使用Javascript中的onclick按钮将数据从表单提交到表 - I want to submit data from form to table using onclick button in Javascript 单击提交按钮 Javascript HTML 后显示表格数据 - Display table data after clicking on submit button Javascript HTML 如何在不使用提交按钮的情况下从html表单传递值 - How to pass value from html form without using submit button 单击提交按钮时,将在javascript中创建的动态生成的html表保存并传递给php - preserve and pass dynamically generated html table created in javascript to php when submit button is clicked 单击表单的“提交”按钮,如何将数据从HTML保存到Excel? - How to save data from HTML to excel, on click on “submit” button of form? 表单提交按钮onClick JavaScript功能 - Form submit button onClick JavaScript function 如何将数据从onclick按钮传递到变量 - How to pass data from onclick button to variable 如何使用javascript和node.js-mysql而不使用php将HTML表单数据提交到MySql数据库表中? - How can I submit HTML form data into MySql database table using javascript along with node.js - mysql and without php?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM