简体   繁体   English

PHP AJAX在表单提交时确认

[英]PHP AJAX Confirm on Form Submit

I have a small form which contains a first name, last name and a date. 我有一个小的表格,其中包含名字,姓氏和日期。 On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. 单击提交表单后,我希望它检查数据库中是否有重复的条目(使用Ajax),如果已经有1个以上的条目,请显示一个确认窗口,以确认另一个提交。 The confirm shouldn't show if there aren't any entries. 如果没有任何条目,则不应显示确认。

For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. 由于某种原因,它似乎在没有Ajax PHP页面结果的情况下显示确认。 If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. 如果我在xmlHttp.send(null)行之后引入警报,则它会从PHP获取文本(根据需要),使我觉得我误解了代码的执行顺序。 Here is the code: 这是代码:

Javascript: Javascript:

    function check_duplicates() {
        var first = document.getElementById('first_name').value;
        var last = document.getElementById('last_name').value;
        var date = document.getElementById('event_date').value;

        var xmlHttp = GetXmlHttpObject();
        if (xmlHttp == null) {
            alert ("Your browser does not support AJAX!");
            return;
        }

        var result = "ERROR - Ajax did not load properly";
        var url="check_duplicate.php";
        url=url+"?first="+first;
        url=url+"&last="+last;
        url=url+"&date="+date;

        xmlHttp.onreadystatechange=function() {
            if(xmlHttp.readyState==4) {
                result = xmlHttp.responseText;
                alert("RESULT="+result);
                if(result != "clean") {
                    var validate = confirm(result);
                    return validate;
                }
            }
        }

        xmlHttp.open("GET",url,true);
        var test = xmlHttp.send(null);
    }
    function GetXmlHttpObject() {
        var xmlHttp = null;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp=new XMLHttpRequest();
        }
        catch (e) {
                // Internet Explorer
                try {
                    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
        }

        return xmlHttp;
    }

PHP: PHP:

// DATABASE CONNECTION INFORMATION REMOVED

$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));

$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
        "Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

if($row['count'] > 0) {
   if($row['count'] == 1) {
      echo "There is already an entry for ".$first." ".$last." on ".
           date('M jS',strtotime($date)).".\n".
           "Are you sure you want to submit this entry?";
   }
   else { // plural version of the same message
      echo "There are already ".$row['count']." entries for ".$first." ".
        $last." on ".date('M jS',strtotime($date)).".\n".
       "Are you sure you want to submit this entry?";
   }
} else {
   echo "clean";
}

Here is an answer using synchronous AJAX. 这是使用同步AJAX的答案。 This way, you don't have to overload the default form handling to get it to work. 这样,您不必超载默认的表单处理即可使其正常工作。 However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts. 但是,在运行确认请求时, 所有javascript都将被阻止 ,这意味着无论确认请求持续多长时间,您的网页似乎都会停止运转。

This function will return true if the record should be added, and false otherwise. 如果应添加记录,此函数将返回true,否则返回false。

function check_duplicates() {
    var first = document.getElementById('first_name').value;
    var last = document.getElementById('last_name').value;
    var date = document.getElementById('event_date').value;

    var xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return false;
    }

    var result = "ERROR - Ajax did not load properly";
    var url="check_duplicate.php";
    url=url+"?first="+encodeURIComponent(first);
    url=url+"&last="+encodeURIComponent(last);
    url=url+"&date="+encodeURIComponent(date);

    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);

    var validated = true;
    var result = xmlHttp.responseText;

    if (result != 'clean')
        validated = confirm("RESULT="+result);

    return validated;
}

This line of code return undefined . 这行代码返回undefined

 var test = xmlHttp.send(null);

What you have to understand is that the send() call returns immediately and Javascript keeps running. 您需要了解的是send()调用会立即返回,并且Javascript会继续运行。 Meanwhile, your AJAX request is running in the background. 同时,您的AJAX请求在后台运行。 Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code. 另外,请求完成后,将onreadystatechange处理程序,无论该过程耗时10ms还是100s,其余代码都不会接收其返回值。

I think what you wanted to submit the form AFTER the confirmation was finished. 我认为您要在确认完成后提交表格。 You only know when the request is finished from inside your onreadystatechange handler. 您仅从onreadystatechange处理程序内部知道请求何时完成。 The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form. 这里的问题是,为了等待AJAX​​请求完成,您必须覆盖表单的默认行为。

You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation. 您需要在表单提交事件上调用preventDefault() ,然后在确认后手动提交数据。

    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4) {
            var confirmed = false;
            var result = xmlHttp.responseText;
            if (result == "clean")
                confirmed = true;
            else
                confirmed = confirm("RESULT="+result);

            if (confirmed) {
                var url = "addData.php";
                url=url+"?first="+encodeURIComponent(first);
                url=url+"&last="+encodeURIComponent(last);
                url=url+"&date="+encodeURIComponent(date);
                window.location = url;
            }
        }
    }

Also, when you're building your URL you should use encodeURIComponent. 另外,在构建URL时,应使用encodeURIComponent。

    url=url+"?first="+encodeURIComponent(first);
    url=url+"&last="+encodeURIComponent(last);
    url=url+"&date="+encodeURIComponent(date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM