简体   繁体   中英

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. anyone can help me what is going wrong. even I used serialize() method also but no result.

<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.

 <?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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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