Home > Software engineering >  Ajax call inserts to Mysql twice after submitting form
Ajax call inserts to Mysql twice after submitting form

Time:02-19

I have a problem with a insert and update on my form that is handled by a AJAX call. Everything works fine if the required field(s) is filled out (HTML, Ajax and PHP).

If I try to submit without filling the required fields the error message is set as intended but when I adjust it, fill it out and submit it the insert gets fired twice.

I'm new to this so the possibility is there that I'm making a stupid mistake somewhere but I really don't see it. Thanks in advance for the help.

Here are the codes I use:

HTML:

<form method="post" id="formStepVisit">
  <div >
    <label for="firstVisitDate">Datum eerste bezoek*</label> 
    <input id="firstVisitDate" name="firstVisitDate" type="date" value="" >
    <small id="dateHelp" >*Datum eerste bezoek bij klant: <?php echo $Voornaam.' '.$Achternaam;?> is verplicht.</small>
  </div>
  <div >
    <label for="firstVisitfb">Feedback eerste bezoek*</label>
    <textarea  id="firstVisitfb" name="firstVisitfb" rows="4"></textarea>
    <small id="fbHelp" >*Feedback eerste bezoek bij klant: <?php echo $Voornaam.' '.$Achternaam;?> is verplicht.</small>
  </div>
  <input type="hidden" id="sid" name="sid" value="<?php echo $sid?>">
  <button type="submit" id="btnFaseVisit" >Voltooid</button>
</form>

JQuery / AJAX:

$(document).on('click', '#btnFaseVisit', function(){
  if( buttonclicked = true ){
    $('#formStepVisit').on('submit', function (e) { 
      var formData = {
        visitDate: $("#firstVisitDate").val(), 
        fb: $("#firstVisitfb").val(),
        sid: $("#sid").val()
      };
        $.ajax({
        type: "POST",
        url: "actions/processVisit.php",
        data: formData,
        dataType: "json",
        encode: true,
        }).done(function (data) {
          console.log(data);
          if (!data.success) {
            if (data.errors.fb) {
              $("#firstVisitfb").addClass("has-error");
              $("#fbHelp").prepend('<div >'   data.errors.fb   "</div>");
            }
            if (data.errors.visitDate) {
              $("#firstVisitDate").addClass("has-error");
              $("#dateHelp").prepend('<div >'   data.errors.visitDate   "</div>");
            }
          } else {  
              $("#formStepVisit").html('<div >'   data.message   "</div>");
              setTimeout(window.location.reload(true),3000);
          }
        });
      e.preventDefault();
    });
  }
});

PHP:

//Set empty errors and response
$errors = [];
$data = [];

if (empty($_POST['visitDate'])) {
    $errors['visitDate'] = 'Datum is verplicht';
}

if (empty($_POST['fb'])) {
    $errors['fb'] = 'Feedback is required';
}

if (empty($_POST['sid'])) {
    $errors['sid'] = 'Sid is required.';
}

//Sanitation
$visitDate = preg_replace("([^0-9/])", "", $_POST['visitdate']);
$visitDate = date("Y-m-d");
$fb = cleanData ( $_POST['fb'] );
$sid = cleanData ( $_POST['sid'] );
$stepComplete = true;


if (!empty($errors)) {
    $data['success'] = false;
    $data['errors'] = $errors;
} else {
    $sql = "UPDATE laadpalen SET visitDate = ?, visitFB = ?, faseVisitComp =?, fase='offerte' WHERE sid=?";
    if($stmt = mysqli_prepare($con, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "ssis", $visitDate, $fb, $stepComplete, $sid);

        if(mysqli_stmt_execute($stmt)){
            $data['success'] = true;
            $data['message'] = 'Update Succesvol! U wordt omgeleid in <span id="seconden">3</span> ';
        }
    } 
    $sql2 = "INSERT INTO laadpalenSteps (sid, datum, fase, feedback) VALUES (?, NOW(),? , ?)";
    $fase = "bezoek";
    if($stmt = mysqli_prepare($con, $sql2)){
        mysqli_stmt_bind_param($stmt, "sss", $sid, $fase, $fb);
        mysqli_stmt_execute($stmt);
    }
  
}

echo json_encode($data);
?>

CodePudding user response:

why are you using $(document).on ???

It does submit twice because you are calling the ajax method twice !!!!!

you really need to refactor your code !!

First, Your html should be this: You dont need to use form in this case.

<div>
  <div >
    <label for="firstVisitDate">Datum eerste bezoek*</label> 
    <input id="firstVisitDate" name="firstVisitDate" type="date" value="" >
    <small id="dateHelp" >*Datum eerste bezoek bij klant: <?php echo $Voornaam.' '.$Achternaam;?> is verplicht.</small>
  </div>
  <div >
    <label for="firstVisitfb">Feedback eerste bezoek*</label>
    <textarea  id="firstVisitfb" name="firstVisitfb" rows="4"></textarea>
    <small id="fbHelp" >*Feedback eerste bezoek bij klant: <?php echo $Voornaam.' '.$Achternaam;?> is verplicht.</small>
  </div>
  <input type="hidden" id="sid" name="sid" value="<?php echo $sid?>">
  <button type="submit" id="btnFaseVisit" >Voltooid</button>
</div>

And in your JS code you should verify your empty inputs not in the form when you are not using it !

$(function() {
    $('#btnFaseVisit').on('click', function (e) {   
        
        var formData = {
          visitDate: $("#firstVisitDate").val(), 
          fb: $("#firstVisitfb").val(),
          sid: $("#sid").val()
        };
          $.ajax({
          type: "POST",
          url: "actions/processVisit.php",
          data: formData,
          dataType: "json",
          encode: true,
          }).done(function (data) {
            console.log(data);
            if (!data.success) {
              if (data.errors.fb) {
                $("#firstVisitfb").addClass("has-error");
                $("#fbHelp").prepend('<div >'   data.errors.fb   "</div>");
              }
              if (data.errors.visitDate) {
                $("#firstVisitDate").addClass("has-error");
                $("#dateHelp").prepend('<div >'   data.errors.visitDate   "</div>");
              }
            } else {  
                $("#formStepVisit").html('<div >'   data.message   "</div>");
                setTimeout(window.location.reload(true),3000);
            }
          });
        e.preventDefault();
      });
});

CodePudding user response:

It's redundant that you are calling a submit function on a button that already has type=submit. So what's happening is upon clicking the button, your event is called and the submit function is also called.

You could simply just keep .submit function and remove the event on the button but if you want to retain your code, you could try adding e.stopPropagation at the top;

$(document).on('click', '#btnFaseVisit', function(e){
   e.stopPropagation();

https://api.jquery.com/event.stopPropagation/

  • Related