0

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);

?>
blex
  • 24,941
  • 5
  • 39
  • 72
Ahmad
  • 97
  • 1
  • 7
  • 1
    you forgot to end your if statement. Add a closing `}` at the end of it - you also need to `echo` the `$result` in some way – Nick Parsons Dec 23 '18 at 11:50
  • 1
    *not working properly* not enough to describe your problem .. you can tell us what is the output of `alert(data);` – Mohamed-Yousef Dec 23 '18 at 11:55
  • Please provide as much information as you can. any errors from error.log, or copied and pasted from your outout is welcomed as an aid to help us help you – JoSSte Dec 23 '18 at 12:09
  • serialize won't include the submit button – charlietfl Dec 23 '18 at 13:12
  • Also: your `serialize()` call will not include `submit` in the arguments list, as a submit button is not treated in the same way as input fields or select elements are. Therefore the property `$_POST['submit']` will never be set in new.php. – Carsten Massmann Dec 23 '18 at 13:15

1 Answers1

0

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.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • No result, in alert I give false message nothing more. – Ahmad Dec 24 '18 at 05:33
  • It doesn't provide any error, even I removed the $_POTS['submit'] from new.php but no result just it show false in alert box nothing more – Ahmad Dec 24 '18 at 05:39