AJAX: повторяющиеся записи - PullRequest
       0

AJAX: повторяющиеся записи

2 голосов
/ 05 сентября 2011

Я использую AJAX для создания новой строки в таблице с помощью SQL. Мой код довольно прост, но я заметил, что иногда он создает повторяющиеся записи (иногда даже 3) в базе данных. Есть ли способ предотвратить это? Вот мой код (отправлено через php echo).

ОБНОВЛЕННАЯ ГЛАВНАЯ СТРАНИЦА

echo "
    <script language='javascript'>


$('#newreportBTN').live(\"click\", function() {

 //Get variables from boxes
        var data = $(\"#newreport\").serialize();

    $.ajax({
            type: 'POST',
            url: \"report_new.php\",        
            data: data,
           success: function (html) {              
                //if process.php returned 1/true (send mail success)
                if (html==1) {                  
                    //Send notification to user
                     $('#adminReportInfo').fadeOut(300);

                //if process.php returned 0/false (send mail failed)
                } else alert('Sorry, unexpected error. Please try again later.');               
            }       
        });

        //cancel the submit button default behaviours
        return false;
    });


    </script>
    ";

report_new.php

<?php
//Start session
session_start();

//Include database connection details
require_once('config.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}



$company = $_POST['company'];
$claimnumber = $_POST['claimnumber'];
$fullname = $_POST['fullname'];
$dateofloss = $_POST['dateofloss'];
$foruser = $_POST['foruser'];
$status = $_POST['status'];


//Input Validations
if($company == '') {
    $errmsg_arr[] = 'Company Missing';
    $errflag = true;
}
if($claimnumber == '') {
    $errmsg_arr[] = 'Claim # Missing';
    $errflag = true;
}
if($fullname == '') {
    $errmsg_arr[] = 'Full name missing';
    $errflag = true;
}


//If there are input validations, redirect back to the registration form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: user_error.php");
    exit();
}

//Create INSERT query
$qry = "INSERT INTO documents (company, claimnumber, fullname, dateofloss, foruser, status) VALUES ('$company', '$claimnumber','$fullname','$dateofloss','$foruser','$status')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    //header("location: admin.php?status=new");
    echo '1';
    exit();
}else {
    die("Query failed");
    echo mysql_error();
}
?>

Ответы [ 5 ]

1 голос
/ 05 сентября 2011

Проверьте следующее:

  • Убедитесь, что вы связываете событие только один раз.

  • Вы можете отменить привязку всех событий для вашего конкретного селектораи связать это снова.

  • Вы также можете добавить метод предотвращение ошибок (http://api.jquery.com/event.preventDefault/)

ПРИМЕР: http://jsfiddle.net/FZ7Dk/

$(function() {

    $('#newreportBTN').live('click', function(e) {
        e.preventDefault();

        /*Code here*/

        /*on success*/
        $('#newreportBTN').unbind();
        $('#newreportBTN').bind('click');
    });

});
0 голосов
/ 06 сентября 2011

Наконец-то понял это.Для тех, кто столкнулся с этой проблемой в будущем:

Я использовал PHP echo для распечатки кода javascript при нажатии элемента.ИЗБЕГАЙТЕ ЭТОГО, ЕСЛИ ВОЗМОЖНО.Я думаю, что происходило то, что фрагмент кода мог повторяться несколько раз, возможно, вызывая его запуск несколько раз.Я переместил этот код из эха PHP в раздел заголовка на странице HTML (хотя он не всегда может быть использован, он предотвращает эту ошибку).

0 голосов
/ 06 сентября 2011

Это несколько не по теме, но вы можете значительно упростить отправку формы, например:

<script type="text/javascript">

    $('#newreportBTN').click(function(e) {

        var data = $("#your_form_id_here").serialize();

        $.post({
            url: "report_new.php",        
            data: data,
            success: function (html) {              
                // handle result             
            }       
        });

        //cancel the submit button default behaviours
        e.preventDefault();
    });

</script>

Это также следует соглашению (на которое намекают сами HTTP-глаголы), что GET-запросы должны использоваться только для извлечения данных, в то время как POST или PUT используются для отправки данных на сервер для обработки. Надеюсь, это полезно ...

0 голосов
/ 05 сентября 2011
function addtoGrid(empid){

                var arraycp=new Array();

                var arraycp = $.merge([], myArray2);

                var items= new Array();
                for(i=0;i<empid.length;i++){

                    items[i]=empid[i];
                }

                var u=1;
                $.each(items,function(key, value){

                    if(jQuery.inArray(value, arraycp)!=-1)
                    {

                        // ie of array index find bug sloved here//
                        if(!Array.indexOf){
                            Array.prototype.indexOf = function(obj){
                                for(var i=0; i<this.length; i++){
                                    if(this[i]==obj){
                                        return i;
                                    }
                                }
                                return -1;
                            }
                        }

                        var idx = arraycp.indexOf(value);
                        if(idx!=-1) arraycp.splice(idx, 1); // Remove it if really found!
                        u=0;

                    }
                    else{

                        arraycp.push(value);

                    }


                }


            );

                $.each(myArray2,function(key, value){
                    if(jQuery.inArray(value, arraycp)!=-1)
                    {

                        // ie of array index find bug sloved here//
                        if(!Array.indexOf){
                            Array.prototype.indexOf = function(obj){
                                for(var i=0; i<this.length; i++){
                                    if(this[i]==obj){
                                        return i;
                                    }
                                }
                                return -1;
                            }
                        }

                        var idx = arraycp.indexOf(value); // Find the index
                        if(idx!=-1) arraycp.splice(idx, 1); // Remove it if really found!
                        u=0;

                    }
                    else{


                    }


                }


            );
                $.each(arraycp,function(key, value){
                    myArray2.push(value);
                }


            );if(u==0){

                }
                var courseId1=$('#courseid').val();
                $.post(

                "<?php echo url_for('payroll/LoadGrid') ?>", //Ajax file



                { 'empid[]' : arraycp },  // create an object will all values

                //function that is called when server returns a value.
                function(data){


                    //var childDiv;
                    var childdiv="";
                    var i=0;

                    $.each(data[0], function(key, value) {
                        var word=value.split("|");
                                    var diable='<?php echo $disabled; ?>';
                                    childdiv="<div class='pagin' id='row_"+i+"' style='padding-top:10px;'>";
                                    childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[0]+"</div>";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:220px;'>";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[1]+"</div>";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[2]+"</div>";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:75px;'>";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[3]+"</div>";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:75px;'>";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[4]+"</div>";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:50px;'>";
                                    childdiv+="<input style='width:50px; height:13px; padding-left:0px; ' id='chkconfirm'  name='chkconfirm[]' type='checkbox'  value='1' "+diable+" '<?php if($SalarayIncrement->inc_confirm_flag==1){ echo "checked"; }; ?>' />";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
                                    childdiv+="<input style='width:90px; height:13px; padding-left:0px; ' id='txtcomment'  name='txtcomment[]' type='text'  maxlength='200' "+diable+"  value='<?php echo $SalarayIncrement->inc_comment; ?>' />";
                                    childdiv+="</div>";

                                    childdiv+="<div class='centerCol' id='master' style='width:70px;' >";
                                    childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'><a href='#' style='width:70px;'  onclick='deleteCRow("+i+","+word[8]+")'><?php echo __('Remove') ?></a>";
                                    childdiv+="<input type='hidden' name='hiddenPreviousSalary[]' value="+word[2]+" >";
                                    childdiv+="<input type='hidden' name='hiddenNewSalary[]' value="+word[3]+" >";
                                    childdiv+="<input type='hidden' name='hiddenIncrement[]' value="+word[4]+" >";
                                    childdiv+="<input type='hidden' name='hiddenEmpNumber[]' value="+word[8]+" >";
                                    childdiv+="<input type='hidden' name='hiddenPreviousSal[]' value="+word[5]+" >";
                                    childdiv+="<input type='hidden' name='hiddenNewSal[]' value="+word[6]+" >";
                                    childdiv+="<input type='hidden' name='hiddenGrade[]' value="+word[7]+" >";
                                    childdiv+="</div>";
                                    childdiv+="</div>";
                                    childdiv+="</div>";
                                    //

                                    $('#tohide').append(childdiv);


                        k=i;
                        i++;
                    });
                    pagination++;

                    $(function () {

                       if(pagination > 1){
                       $("#tohide").depagination();
                       }
                        $("#tohide").pagination();
                    });
                $.each(data[1], function(key, value) {
                        var Employee=value.split("|");
                        alert(Employee[0]+" - "+Employee[1]+"<?php echo __(" can not perform increment, please edit the Basic salaray") ?>");
                });
                },

                //How you want the data formated when it is returned from the server.
                "json"

            );


            }

Передайте свои идентификаторы в функцию addTogrid в виде массива, который будет предотвращать дублирование данных

0 голосов
/ 05 сентября 2011

Этот код не должен создавать более одной записи, если вы не нажимаете кнопку более одного раза. Также вам не нужно убегать нажмите здесь

$('#newreportBTN').live(\"click\" ...

Также попробуйте использовать .click() вместо .live()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...