NoReceipt4Panda NoReceipt4Panda - 6 months ago 13
SQL Question

Why does PHP MySQL INSERT through AJAX call only happen sometimes?

I have a page with a modal. The modal code is in its own PHP file called "tour-modal.php":

<div class="modal fade" id="tourModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
</div>
<div class="modal-body">
<div class="errors2"></div>
<form class="tour-card" action="insert.php" method="post">
<div class="form-group col-sm-12">
<input type="text" class="form-control" id="firstNameTourCard" placeholder="First Name"/>
<input id="middleInitialTour" type="hidden" value="">
<input type="text" class="form-control" id="lastNameTourCard" placeholder="Last Name"/>
<input type="email" class="form-control" id="emailTourCard"/>
<input type="tel" class="form-control" id="phoneTourCard"/>
<select class="form-control" id="tourDate">
<option>May 25 2016</option>
<option>May 28 2016</option>
</select>
<select class="form-control" id="tourTime">
<option>1:00 PM</option>
<option>1:30 PM</option>
<option>2:00 PM</option>
</select>
</div>
<input id="tour-btn" type="button" value="SUBMIT" class="btn btn-default tour-button"/>
<button type="button" class="btn btn-default tour-button" data-dismiss="modal">CLOSE</button>
</form>
</div>
</div>
</div>
</div>


On this same file, I have a jQuery/AJAX script like this:

<script>
jQuery("#tour-btn").click(function (e) {
var str = "firstNameTourCard=" + jQuery("#firstNameTourCard").val()
+ "&lastNameTourCard=" + jQuery("#lastNameTourCard").val()
+ "&emailTourCard=" + jQuery("#emailTourCard").val()
+ "&phoneTourCard=" + jQuery("#phoneTourCard").val()
+ "&tourDate=" + jQuery("#tourDate").val()
+ "&tourTime=" + jQuery("#tourTime").val()
+ "&middleInitialTour=" + jQuery("#middleInitialTour").val();

jQuery.ajax({
type: "post",
url: "/wp-content/themes/myTheme/tour-form.php",
data: str,
dataType: "json",
success: function(result) {
if (result.success == 1) {
console.log ('success');
jQuery('#tourModal').modal('hide');
} else {
console.log ('failure');
jQuery(".errors2").html(result.errors2);
}
}
});
});
</script>


Lastly, I have the "tour-form.php" file which is referenced in the AJAX call:

<?php
try {
$db = new PDO('mysql:host=localhost;dbname=MYDBNAME;charset=utf8',
'USERNAME',
'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}

catch(PDOException $ex) {
echo "did not connect...";
}


$firstNameTourCard = trim(isset($_POST['firstNameTourCard']) ? $_POST['firstNameTourCard'] : '');
$lastNameTourCard = trim(isset($_POST['lastNameTourCard']) ? $_POST['lastNameTourCard'] : '');
$emailTourCard = trim(isset($_POST['emailTourCard']) ? $_POST['emailTourCard'] : '');
$phoneTourCard = trim(isset($_POST['phoneTourCard']) ? $_POST['phoneTourCard'] : '');
$tourDate = trim(isset($_POST['tourDate']) ? $_POST['tourDate'] : '');
$tourTime = trim(isset($_POST['tourTime']) ? $_POST['tourTime'] : '');

if ($_POST['middleInitialTour'] != '') {
$result = array(
"success" => 1);
die(json_encode($result));
}


$errors2 = Array();
if (sizeof($_POST) > 0) {
if ($emailTourCard === '' || !filter_var($emailTourCard, FILTER_VALIDATE_EMAIL)) {
$errors2[] = '<span style="color:red;"> Please enter a valid email address. </span>';
}
}

if (sizeof($errors2) > 0 || sizeof($_POST) == 0) {
$result = array(
"errors2" => implode("<br/>", $errors2),
"success" => 0);
die(json_encode($result));
}

$randID2 = md5(uniqid(rand(), true));

$sql="INSERT INTO tours (id, first_name, last_name, email, phone, tour_date, tour_time, signup_date)
VALUES
('".$randID2."', '".$firstNameTourCard."', '".$lastNameTourCard."', '".$emailTourCard."', '".$phoneTourCard."', '".$tourDate."', '".$tourTime."', NOW())";
$sth = $db->prepare($sql);
$sth->execute();


$result = array(
"success" => 1);
die(json_encode($result));

?>


The problem is that only 1 out of 5 times that I try this the SQL query actually executes. The AJAX call is called, and the PHP file sends a success over, the modal closes, but the
INSERT
statement is rare to actually work. Can anyone see anything wrong?

Answer

Using material from almost every comment for my code, I went ahead and found my answer, only a few tweaks needed to be made. Thanks everybody!

The very end of "tour-form.php":

$sth = $db->prepare($sql);
#success = $sth->execute();

$result = array(
"success" => $success);
die(json_encode($result));

New script:

jQuery("#tour-btn").click(function (e) {
    jQuery('#tour-btn').attr("disabled", true); 

    function joinTour(str) {
        jQuery.ajax({       
            type: "post",   
            url: "/wp-content/themes/myTheme/tour-form.php",
            data: str,  
            dataType: "json",   
            success: function(result) {         
                if (result.success == 1) {          
                    console.log ('success');        
                    jQuery('#tourModal').modal('hide');     
                    jQuery('#tour-btn').attr("disabled", false);     
                } else {    
                    console.log ('failure');    
                    if (result.errors2) {
                        jQuery(".errors2").html(result.errors2);    
                        jQuery('#tour-btn').attr("disabled", false);     
                    }
                    if (!result.errors2) {
                        setTimeout(function () {
                            joinTour(str);
                        }, 500)
                    }
                }       
            }   
        });
    }

    var str = $(form").serialize();

    joinTour(str);
});