为什么我的提交按钮不提交给mySQL?

时间:2019-10-04 19:37:43

标签: php html mysql ajax forms

我有一个php表单,我将其称为“ php1”,该表单使用ajax从mySQL db填充输入文本框。为此,它使用辅助页面,我将其称为“ php2”。在php2上,有一个提交“按钮”,用于将任何更改提交给mySQL db。除了提交外,每个方面的工作都很好,除非我自己测试php2,然后它才能提交给数据库。我在做什么错了?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    function myBlur(str){
        if (str == "") {
        document.getElementById("demo").innerHTML = "You Must Enter a Device Name! <br>";
            $("#demo").css("background-color","red");
            $("#Name").css("background-color","red");
        return;
    } else {
        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 (this.readyState == 4 && this.status == 200) {
                document.getElementById("form1").innerHTML = this.responseText;
}
        };
        xmlhttp.open("GET","php2.php?q="+str,true);
        xmlhttp.send();
    }
}
    </script>

这是第二页。

        <fieldset><legend>Input</legend>
                  <div width="100%" id="form1">
        <div id="demo"><br></div><br>
        <form method="post" action="php1.php">
          Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="<?php echo $Name ?>" onChange="myBlur(this.value)">
          MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="<?php echo $MAC ?>">
          Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="<?php echo $Own ?>">
            Type: <select name="Type" id="Type" required="required" readonly="true" value="<?php echo $Type ?>">
              <option value=""></option>
              <option value="Desktop">Desktop</option>
              <option value="Laptop">Laptop</option>
              <option value="Server">Server</option>  
              <option value="Monitor">Monitor</option>
              <option value="Printer">Printer</option>
              <option value="Phone">Phone</option>
                  </select>
        <br>
        </div>
            </fieldset>
                </form>

那是php1的表单代码

    $sql = "SELECT * FROM $table WHERE Name = '$q'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $N=$row["Name"];
            $MA=$row["MAC"];
            $Ow=$row["Own"];
            $Ty=$row["Type"];
            echo "<tr>";
            echo "<form  method='post' action='php1.php' id='UpAss'>",UpAss,"
            <br><br>
                Device Name: <input type='text' id='Name' name='Name' value=".$N." onBlur='myBlur(this.value)'>
                MAC Address: <input type='text' id='MAC' name='MAC' readonly='True' autocomplete='off' value=". $MA.">
                Owner or Location: <input type='text' id='Own' name='Own' value=". $Ow.">
                Type: <select id='Type'>
                    <option value='".$Ty."'>". $Ty."</option>
                    <option value='Desktop'>Desktop</option>
                    <option value='Laptop'>Laptop</option>
                    <option value='Server'>Server</option>  
                    <option value='Monitor'>Monitor</option>
                    <option value='Printer'>Printer</option>
                    <option value='Phone'>Phone</option>
                    <option value='iPhone'>iPhone</option>
                </select>
            echo "<input type='submit' id='Usubmit' value='Update Asset' form='UpAss' onClick='myUpdate()'></input></form>";
        }
function myUpdate()
    {    
// Create connection
$connU = new MySQLi($db_host, $db_user, $db_pass, $db_name, $db_port);
// Check connection
if ($connU->connect_error) {
    die("Connection failed: " . $connU->connect_error);
}
  $Name = ($_POST["Name"]);
  $MAC = ($_POST["MAC"]);
  $Own = ($_POST["Own"]);
  $Model = ($_POST["Model"]);
  $OS = ($_POST["OS"]);
  $Type = ($_POST["Type"]);
$sqlU = "REPLACE INTO SET $table SET MAC='$MAC', Own='$Own', Type='$Type' WHERE Name=$Name;";
if ($connU->query($sqlU) === TRUE) {
            echo "PPC-".$Name." Has Been Updated!";
} else {
    echo "Error: " . $sqlU . "<br>" . $connU->error;
}
$connU->close();
    }
    if(isset($_POST['Usubmit']))
    {
        myUpdate();
    }
?>

这是将表单从php2加载到php1的代码。我确信这很简单,我很想念,希望能对您有所帮助。所有这些代码都很好用,但是提交。  *(我故意将数据库信息排除在此代码之外。)

1 个答案:

答案 0 :(得分:0)

1。)用于发布(通过ajax插入,更新和删除)

这将使您开始如何通过ajax jquery发布。您可以在代码上看到注释

您还可以看到,表单参数设置为id="add_content",这在jquery ajax调用中得到了体现

<form method="post" id="add_content">

您还可以在html div的正文中看到单击按钮并因此显示后端结果时显示图像加载器的情况

   

请参阅示例 post.html

<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
  type="text/javascript" charset="utf-8"></script>


<script>

$(document).ready(function(){
$('#add_content').on('submit', function(e){
e.preventDefault();
alert('ok');

// display a loading image and message
$('#loader').fadeIn(400).html('<img src="loader.gif" align="absmiddle">&nbsp;<span class="loading">Please Wait.. submiting form..</span>');

        $.ajax({

            type:'POST',
            url:'post.php',
            data:$(this).serialize(),
                        crossDomain: true,
            cache:false,
            success:function(msg){
// hide loader to display result
$('#loader').hide();
                $('#showposts').fadeIn('slow').prepend(msg);

            }

        });


});
});


</script>
  </head>
    <body>

    <div id="loader"> </div>
    <div id="showposts"> </div>


<form method="post" id="add_content">
          Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="100" onChange="myBlur(this.value)">
          MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="1001">
          Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="nancy read only">
            Type: <select name="Type" id="Type" required="required" readonly="true" value="nancy type">
              <option value=""></option>
              <option value="Desktop">Desktop</option>
              <option value="Laptop">Laptop</option>
              <option value="Server">Server</option>  
              <option value="Monitor">Monitor</option>
              <option value="Printer">Printer</option>
              <option value="Phone">Phone</option>
                  </select>
        <br>
        </div>
            </fieldset>
<input type="submit" name="add" id="add"  value="Add" />

                </form>

</body>

post.php

的示例
<?php

// use strip_tags to avoid html injection that can also leads to xss attck
// sample with assets number

$asset_number= strip_tags($_POST['Name']);
$MAC= $_POST['MAC'];
$Own= $_POST['Own'];
$Type= $_POST['Type'];

// you can check for emptiness eg.

if($asset_number ==''){

echo "asset number is empty";
exit();
}else{

echo "success. my assests no is: $asset_number";
}




?>

示例2。

如果您只想获取有或没有发送参数的记录,则可以尝试

如果要从另一个页面调用它,请记住传递jquery库(jquery.min.js)

<script>

$(document).ready(function(){

// set variable payload for formality. though you can pass it to backend as a variable  
var payload= 'Am Nancy Mooree';
var datasend = "payload="+ payload;
        $('#loader1').fadeIn(400).html('<img src="loader.gif" align="absmiddle">&nbsp;<span class="loading">Please Wait.. submiting form..</span>');

        $.ajax({

            type:'POST',
            url:'showresult.php',
            data:datasend,
                        crossDomain: true,
            cache:false,
            success:function(msg){
            $('#loader1').hide();   

                $('#listposts').fadeIn('slow').prepend(msg);

            }


        });


});






</script>

<div id="loader1"></div>
<div id="listposts"></div>

showresult.php

<?php

// assuming you are sending a post or get variables to query database
$payload= strip_tags($_POST['payload']);

// query your database to display result to ajax.

echo $result ="Am from database where payload is: $payload";




?>