首页 > 解决方案 > PHP:Ajax 复制 MySQL 表中的数据

问题描述

您好,我正在尝试使用 Ajax 和 PHP 将表单数据发送到 MySQL 表。当表单字段为空并发送数据时,我确保显示错误消息。弹出这个错误的次数,我得到的印象是,一旦所有字段都正确重新签名,这代表了我表中的条目数。突然,当我查看我的表格时,我发现表格中的数据已在表格中重复。我无法理解这。我的 AJAX 代码是否将数据保存在内存中,然后在正确填写数据后将其发送回 php?下面,我展示了我的 AJAX 代码,它允许我发送表单数据。

function send(){
    $("#form").on('submit',(function(e) {
     e.preventDefault();
     $("#loader").toggle();
    document.getElementById("go").disabled = true;
    var form_data = new FormData();                  
    //alert(form_data);
    $.ajax({
        type: 'POST',
        url: 'send_to.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        //async: false,
        data: new FormData(this),                         
        success: function(data,status){
            if(data == 'success'){
                $("#resultat").html('<strong style="color:green;">Thank you Your transaction has been sent</strong>');
                $("input[type=text]").val(""); // Vider le formulaire
                $("input[type=number]").val(""); // Vider le formulaire
                document.getElementById('loader').style.display = "none";
                document.getElementById("go").disabled = false;
                //location.reload();
                //window.location.replace("./?home&yes");
            }else{
                $("#resultat").html('<strong style="color:red;">'+data+'</strong>');
                document.getElementById("go").disabled = false;
                document.getElementById('loader').style.display = "none";
            }
        }
     });
 }));
}

我的 PHP 代码:

$sql = $mysqli->prepare("INSERT INTO test (user,phone,email) VALUES (?,?,?)");
    $sql->bind_param('sis',$user,$phone,$email);
    if(!$sql->execute()){
        echo ('cant create);
    }else{
    echo 'data created';
  }

标签: javascriptphpajaxduplicatessend

解决方案


推荐阅读