0


I have a html form which gets posted with ajax to process.php and this php file insert data to mysql.

But for some reason, data in the mysql table gets inserted twice. Every time form is submitted, there are two rows inserted into the database with same values.
Can't figure out the way to find what exactly is happening.

index.html

<!DOCTYPE html>
<html>

<head>
  <link data-require="sweet-alert@*" data-semver="0.4.2" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.4.2/sweet-alert.min.css" />
  <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script data-require="sweet-alert@*" data-semver="0.4.2" src="//cdnjs.cloudflare.com/ajax/libs/sweetalert/0.4.2/sweet-alert.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <form class="form-horizontal" name="addSaleForm" id="addSaleForm" method="POST">
    <label>First Name:</label><br>
    <input type="text" name="fname" id="fname"><br>
    <label>Last Name:</label><br>
    <input type="text" name="lname" id="lname"><br>
    <button type="submit" id="submit-btn" name="register">Submit</button>
  </form>

  <!-- Display result/error msg from php file -->
  <div id="status"></div>

</body>

</html>


<script>
  $(document).ready(function(e) {
    $("#addSaleForm").on('submit', (function(e) {
      e.preventDefault();
      HoldOn.open({
        theme: "sk-rect",
        message: "Processing...<br>Please Hold On.",
        backgroundColor: "black",
        textColor: "white"
      });
      $.ajax({
        url: "process.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
          if (data === 'Success') {
            HoldOn.close();
            swal("Processed!!!", "Day End Report is processed successfully", "success");
            setTimeout(function() {
              window.location.href = "http://localhost/numbers/sales.php";
            }, 1200);

            //swal("Processed!!!", "Day End Report is processed successfully", "success");    


          } else {
            document.getElementById("status").className += " alert-danger";
            $("#status").html(data);
            HoldOn.close();
            swal("Error!!!", data, "error");
          }
        },
        error: function() {}
      });
    }));
  });
</script>

process.php

<?php
require 'connect-to-mysql.php';

// Set variables...
$error = "";


if ( isset($_POST['fname'] ) {
  $first = $_POST['fname'];
  $last = $_POST['lname'];

    try {
        if ( $error == "") {
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $dbh->prepare("INSERT into test (Fname, Lname) 
                        VALUES (?, ?)");            

            $values = array($first, $lname);

            if ($stmt->execute($values)) {
                echo "Success";
            }
        }
        else {
            echo $error;
        }
    }
    catch (PDOException $e){
        echo $e->getMessage();
    }
}

?>

EDIT:

Here is the complete and final code I have copied to Planker.
http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview

sohal07
  • 440
  • 8
  • 21
  • 4
    Try checking the network tab in the developer console (ctr+shift+Q on firefox), see if there's more than one ajax call. IF there's only one, you know the problem is in the php file. – Sebastianb May 30 '16 at 12:33
  • error: function() {} ! – Ali.Mojtahed May 30 '16 at 12:36
  • Also check `script.js` if you are doing another submit there – Chintan May 30 '16 at 12:36
  • use `return false` instead of `e.preventDefault();` to block default behavior of submit. – ADreNaLiNe-DJ May 30 '16 at 12:37
  • Possible duplicate of [Prevent Default on Form Submit jQuery](http://stackoverflow.com/questions/6462143/prevent-default-on-form-submit-jquery) – ADreNaLiNe-DJ May 30 '16 at 12:38
  • @ADreNaLiNe-DJ Well, i have no idea and really don't see why `return false;` would work differently than `e.preventDefault();`. The only difference would be event won't propagate but as a form cannot be nested inside any other form, it doesn't make sense – A. Wolff May 30 '16 at 12:45
  • @A.Wolff It's only because returning `false` works and `preventDefault` don't. Did you see this link http://stackoverflow.com/questions/6462143/prevent-default-on-form-submit-jquery ? – ADreNaLiNe-DJ May 30 '16 at 12:50
  • @ADreNaLiNe-DJ `preventDefault` works, otherwise nor `return false;` would. Your posted link is just misleading specially regarding `submit` event. BTW, just reading OP's comment, you would see he made a mistake and this has nothing to do with `return false;` fixing his issue: `Perhaps an older version was cached. Looks to be working now.` – A. Wolff May 30 '16 at 12:58
  • @Sebastian: I use safari on mac, did check the network tab and found there are 2 times 'process.php', how come this is possible? – sohal07 May 30 '16 at 13:10
  • Here is the complete and final code I ave copied to planker. http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview – sohal07 May 31 '16 at 10:31

1 Answers1

0

1.) I tested your code (without script.js and HoldOn function commented) and it runs just fine. So please check script.js

2.) You have two errors in process.php :

Line 8:

if ( isset($_POST['fname'] ) {

You are missing an ) after $_POST['fname']

Line 18:

$values = array($first, $lname);

probably should be :

$values = array($first, $last);
Phiter
  • 14,570
  • 14
  • 50
  • 84
Bearnik
  • 11
  • 1
  • @ Bearnik: Here's the complete code I have copid to planker. http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview – sohal07 May 31 '16 at 10:30
  • ok, I see the new code is full and the problem is ajax usage with **FormValidation** plugin – Bearnik May 31 '16 at 12:58
  • see [FormValidation with AJAX](http://formvalidation.io/examples/ajax-submit/) for more info ... you got formvalidation function and then submit action again – Bearnik May 31 '16 at 13:00
  • 1
    @sohal07 see [example](http://plnkr.co/edit/8eaQIpeGMs2PpUQCSu7l?p=info) changes are in index_new.html – Bearnik May 31 '16 at 13:11
  • Bearnik - Another thing I have noticed, on receiving error msg from the php file, form doesn't get submitted again after correction. The submit button remains disabled afterwards. – sohal07 May 31 '16 at 13:28
  • hmm, strange, just tested and got success with record in db ... please check if every js and php file is in the right place... what error is giving after form submit ? – Bearnik May 31 '16 at 21:55
  • when I purposely throw an error (for example php validation) which I have configured in the php code `$error = "Description is required in Expenses.";`, it displays this error in Sweet Alert but after correcting the error in the form, if I try to submit it, the button is disabled and I have to refresh the page, input all fields again correctly and submit. – sohal07 May 31 '16 at 23:03