关于MYSQL重复条目的AJAX响应

时间:2014-07-06 16:00:24

标签: php jquery mysql ajax

我的代码很好地将信息输入数据库,然后直接在表格中显示,但我想添加一条消息,表明可能存在重复信息。

下面是我的AJAX代码,你可以看到“成功”将新行添加到最后。但是,如果我的PHP脚本返回“重复找到”消息,它就会破坏,因为它不会与表格方案一起流动,所以当我提交新记录时,新记录现在不会出现在表格的末尾。

我想这与调用json_encode发送错误并触发事件有关,但我找不到很多关于使用它的参考

基本上我想要做的是运行消息,这样它就不会破坏$(“。global_table tr:nth-​​last-child(2)”)。after(response);部分当我添加另一行。看看booking.everythingcreative.co.uk的工作实例

$("#insert_record").click(function (e) {
        e.preventDefault();
        if($("#insert_firstname").val()==='')
        {
            alert("Please enter firstname");
            return false;
        }
        if($("#insert_surname").val()==='')
        {
            alert("Please enter surname");
            return false;
        }
        if($("#insert_email").val()==='')
        {
            alert("Please enter email address");
            return false;
        }

        $("#insert_record").hide(); //hide submit button
        $(".global_loading").show(); //show loading image

        //var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
        var firstname = $("#insert_firstname").val(); //build a post data structure
        var surname = $("#insert_surname").val(); //build a post data structure
        var email = $("#insert_email").val(); //build a post data structure
        var dates = $("#insert_dates").val(); //build a post data structure
        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "assets/scripts/ajax.php", //Where to make Ajax calls
        dataType:"text", // Data type, HTML, json etc.
        data: {firstname: firstname, surname: surname, email: email, dates: dates}, //Form variables
        success:function(response){
            $(".global_table tr:nth-last-child(2)").after(response);
            $("#insert_firstname").val(''); //empty text field on successful
            $("#insert_surname").val(''); //empty text field on successful
            $("#insert_email").val(''); //empty text field on successful
            $("#insert_record").show(); //show submit button
            $(".global_loading").hide(); //hide loading image

        },
        error:function (xhr, ajaxOptions, thrownError){
            $("#insert_record").show(); //show submit button
            $(".global_loading").hide(); //hide loading image
            alert(thrownError);
        }
        });
});

以下是我的PHP脚本中的响应代码,但它触发了上述代码的“成功”

<div id="global_duplicate_container">
<div id="global_duplicate">
<div class="header">Duplicate Entry</div>
<table width="100%" border="0" cellpadding="0" class="global_table">
  <tr>
    <td>Candidate Information</td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_firstname"]; ?></td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_surname"]; ?></td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_email"]; ?></td>
  </tr>
  <tr>
    <td><?php echo date('l dS F, Y', strtotime($training_info['training_datetime'])) ?></td>
  </tr>
  <tr>
    <td><a class="button_live" href="#">More Infomation</a>&nbsp;&nbsp;<a class="button_live close_window" href="#">Close</a></td>
  </tr>
</table>
</div>
</div>

编辑:

到目前为止,这是在提交表单时发生的事情: - 使用AJAX,脚本检查数据库以查看条目是否重复 - 如果发现重复,脚本需要告知用户重复并停止脚本

但目前发生以下情况: - ajax.php脚本发回一些HTML,其中javascript类成功,代码作为底部的额外行,但是当脚本再次运行时,这会因为标签现在被标记破坏而中断。 / p>

我需要做的是告诉javascript表单没有成功,并在页面上的其他地方运行div,如下所示:

 if($duplicate == true) { 
//tell hidden message to appear with details from php script
} else { //run standard ajax success code

继承我的PHP:

//Check that fields have been filled *NEEDS UPDATING*
if(isset($_POST["firstname"]) && strlen($_POST["firstname"])>0) {

    //$contentToSave = filter_var($_POST["firstname"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
    $insert_datetime = date('Y-m-d H:i:s');
    $insert_training = filter_var($_POST["dates"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
    $insert_firstname = filter_var($_POST["firstname"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
    $insert_surname = filter_var($_POST["surname"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
    $insert_email = filter_var($_POST["email"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

    //Check database for possible duplicate
    $database_check = mysqli_query($mysqli,"SELECT * FROM booking_customer WHERE customer_firstname='$insert_firstname' AND customer_surname='$insert_surname' AND customer_email='$insert_email'");
    $check_info = mysqli_fetch_assoc($database_check);
    $check_count = mysqli_num_rows($database_check);
    if($check_count >= 1) {

    // Connect to all training dates to attain training day
    $database_training = mysqli_query($mysqli,"SELECT * FROM training_dates WHERE training_id='$insert_training'");
    $training_info = mysqli_fetch_assoc($database_training);

        ?>
        <div id="global_duplicate_container">
<div id="global_duplicate">
<div class="header">Duplicate Entry</div>
<table width="100%" border="0" cellpadding="0" class="global_table">
  <tr>
    <td>Candidate Information</td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_firstname"]; ?></td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_surname"]; ?></td>
  </tr>
  <tr>
    <td><?php echo $check_info["customer_email"]; ?></td>
  </tr>
  <tr>
    <td><?php echo date('l dS F, Y', strtotime($training_info['training_datetime'])) ?></td>
  </tr>
  <tr>
    <td><a class="button_live" href="#">More Infomation</a>&nbsp;&nbsp;<a class="button_live close_window" href="#">Close</a></td>
  </tr>
</table>
</div>
</div>
<?php
        exit;

    } else {

    // Insert sanitize string in record
    $insert_row = $mysqli->query("INSERT INTO booking_customer(customer_added_datetime, customer_added_by, customer_training_table, customer_firstname, customer_surname, customer_email) VALUES('$insert_datetime', '0','$insert_training','$insert_firstname','$insert_surname','$insert_email')");

    if($insert_row)
    {

    // Connect to all training dates to attain training day
    $database_training = mysqli_query($mysqli,"SELECT * FROM training_dates WHERE training_id='$insert_training'");
    $training_info = mysqli_fetch_assoc($database_training);

    // Connect to customer details
    $database_customer = mysqli_query($mysqli,"SELECT * FROM booking_customer WHERE customer_firstname='$insert_firstname' AND customer_surname='$insert_surname' AND customer_email='$insert_email'");
    $customer_info = mysqli_fetch_assoc($database_customer);

         //Record was successfully inserted, respond result back to index page
          $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL
   //echo "</tr>";
   echo "<tr id=\"customer_".$customer_info['customer_id']."\">";
   echo "<td>".$insert_firstname."</td>";
   echo "<td>".$insert_surname."</td>";
   echo "<td>".$insert_email."</td>";
   echo "<td>".date('l dS F, Y', strtotime($training_info['training_datetime']))."</td>";
   echo "<td><a class=\"confirmation button_live\" href=\"tcpdf/PDF/testPDF.php?id=".$customer_info['customer_id']."&version=email\">Send Invitation</a></td>";
   echo "<td><a class=\"confirmation button_live\" href=\"tcpdf/PDF/testPDF.php?id=".$customer_info['customer_id']."&version=download\">Download</a></td>";
   echo "<td>???????</td>";
   echo "<td><a href=\"#\" id=\"delete_".$customer_info['customer_id']."\" class=\"button_delete\">Remove</a></td>";

          $mysqli->close(); //close db connection

    }else{

        //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

    }

}

1 个答案:

答案 0 :(得分:0)

我设法使用以下代码使用eithedog建议的json_encode来解决它

success:function(response){
                var outcome = $.parseJSON(response);
                if(outcome['duplicate'] == "true") {
                    $('#duplicate_firstname').html(outcome['firstname']);
                    $('#duplicate_surname').html(outcome['surname']);
                    $('#duplicate_email').html(outcome['email']);
                    $('#duplicate_training_date').html(outcome['training']);
                    $("#global_duplicate_container").fadeIn();
                } else {
                    var record =    '<tr id="customer_'+ outcome['id'] +'">\
                                    <td>'+ outcome['firstname'] +'</td>\
                                    <td>'+ outcome['surname'] +'</td>\
                                    <td>'+ outcome['email'] +'</td>\
                                    <td>'+ outcome['training'] +'</td>\
                                    <td><a class="confirmation button_live" href="tcpdf/PDF/testPDF.php?id='+ outcome['id'] +'&version=email">Send Invitation</a></td>\
                                    <td><a class="confirmation button_live" href="tcpdf/PDF/testPDF.php?id='+ outcome['id'] +'&version=download">Download</a></td>\
                                    <td>???????</td>\
                                    <td><a href="#" id="delete_'+ outcome['id'] +'" class="button_delete">Remove</a></td>';
                    $(".global_table tr:nth-last-child(2)").after(record);
                }
            },