简体   繁体   English

数据无法通过Ajax,PHP和JQuery提交到数据库中

[英]Data can't submit through ajax, php and jquery in to database

I try to insert data through the ajax, PHP and jquery but the code is not working properly. 我尝试通过ajax,PHP和jquery插入数据,但是代码无法正常工作。 anyone can help me what is going wrong. 任何人都可以帮助我哪里出了问题。 even I used serialize() method also but no result. 即使我也使用serialize()方法,但没有结果。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <form id="myform">
      <label>Username</label> <input name="name" type="text">
      <label>Password</label> <input name="password" type="text">
      <button type="submit" name="submit" id="submit">Save</button>
    </form>

    <script>
      $(document).ready(function() {
        $("#submit").click(function(event) {
          event.preventDefault();
          $.ajax({
            url: "new.php",
            type: 'POST',
            data: $("#myform").serialize(),
            success: function(data) {
              alert(data);
              $('form').trigger("reset");
            }
          });
        });
      });
    </script>
  </body>
</html>

And this is the new.php it means the PHP code in another file. 这是new.php,它表示另一个文件中的PHP代码。

 <?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', 'root');
   define('DB_DATABASE', 'test');
   $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
   if(isset($_POST['submit'])) {
     $username=$_POST['name'];
     $password=$_POST['password'];

     $sql="INSERT INTO ourteam(name, position) VALUES ('$username','$password')";
     $result=mysqli_query($db,$sql);

?>

Your issue is that this method expects a response from the server in-order to be able to store data as the server response. 您的问题是此方法要求服务器响应,以便能够将数据存储为服务器响应。

success: function(data) {}

You can return this data by outputting it using echo, which we will also json_encode() for the JS to be able to understand the output. 您可以通过使用echo将其输出来返回此数据,我们还将使用json_encode()来使JS能够理解输出。

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'test');

header('Content-Type: application/json'); # Declare what content type we are returning

$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

if(empty(array_diff(array('name', 'password'), array_keys($_POST)))) {
    $stmt = $db->prepare('INSERT INTO ourteam(name, position) VALUES (?, ?)');
    $stmt->bind_param('ss', $_POST['name'], $_POST['password']);
    die(json_encode($stmt->execute())); # die() will halt the program here so no other instructions are executed
}

I updated your code to use prepared statements to prevent SQL Injections . 我更新了您的代码以使用准备好的语句来防止SQL注入

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM