0

The following code successfully submits data to a mysql database. However, the form does not show error when fields are blank and it will not populate the div with the success message when it successfully inserted the data. The php file below shows that if insert is a success the result variable is set to 1 which is reflected in the condition in the if else conditions for the ajax.

<body>
 <div id = "container" >
   <h3>jQuery AJAX Post method example with php and MySQL</h3>
   <p><strong>Please fill in the form and click save.</strong></p>
   <div id="message"></div>
    <form name='form1'>
      <table align = "">
        <tr><td></td></tr>
         <tr>
            <td>
              <label>First Name:</label>&nbsp;
            </td>
            <td>
              <input type='text' placeholder='First Name' name='first_name' id= 'first_name' required ><br />
            </td>
          </tr>
          <tr>
            <td>
                <label>Last Name:</label>&nbsp;
            </td>
            <td>
              <input type='text' placeholder='Last Name' name='last_name' id='last_name' required ><br />
            </td>
          </tr>
          <tr>
            <td>
              <label>Email:</label>&nbsp;
            </td>
            <td>
              <input type='email' name='email' placeholder='Email' id='email' required ><br />
            </td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td>
              <input class='btn' type="button" id = "saveusers" value = "Save" />
            </td>
          </tr>
        </table>
    </form>
  </div>
  <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script type="text/javascript">
    $(function(){
        $("#saveusers").on('click', function(){
            var first_name  = $("#first_name").val();
            var last_name   = $("#last_name").val();
            var email       = $("#email").val();

            $.ajax({
              method: "POST",
              url:    "saverecords_ajax.php",
              data: { "first_name": first_name, "last_name": last_name, "email": email},
             }).done(function( data ) {
                var result = $.parseJSON(data);
                var str = '';
                var cls = '';
                if(result == 1) {
                  str = 'User record saved successfully.';
                  cls = 'success';
                }else if( result == 2) {
                  str = 'All fields are required.';
                  cls = 'error';
                }else if( result == 3) {
                  str = 'Enter a valid email address.';
                  cls = 'error';
                }else{
                  str = 'User data could not be saved. Please try again';
                  cls = 'error';
                }
              $("#message").show(3000).html(str).addClass('success').hide(5000);
          });
       });
     });

  </script>
</body>

saverecords_ajax.php file

<?php

$host         = "localhost";
$username     = "root";
$password     = "password";
$dbname       = "testing";
$result = 0;

/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection */
if ($conn->connect_error) {
     die("Connection to database failed: " . $conn->connect_error);
}

/* Get data from Client side using $_POST array */
$fname  = $_POST['first_name'];
$lname  = $_POST['last_name'];
$email  = $_POST['email'];
/* validate whether user has entered all values. */
if(!$fname || !$lname || !$email){
  $result = 2;
}elseif (!strpos($email, "@") || !strpos($email, ".")) {
  $result = 3;
}
else {
   //SQL query to get results from database
   $sql    = "insert into users (first_name, last_name, email) values (?, ?, ?)  ";
   $stmt   = $conn->prepare($sql);
   $stmt->bind_param('sss', $fname, $lname, $email);
   if($stmt->execute()){
     $result = 1;
   }
}
echo $result;
$conn->close();
Dharman
  • 30,962
  • 25
  • 85
  • 135

0 Answers0