Ajax代码不起作用

时间:2014-04-04 14:02:00

标签: javascript php ajax

所以我有这个程序,用户进入一个城市和一个国家。该程序在数据库中查看该城市是否已经存在,如果是,我是否使用ajax显示警告消息,如果不是,我将城市添加到数据库。

这是表格:

<form action="addCity.php" method="get" onsubmit="return validateCityInfoForm();">

onsumbit我调用了如下所示的javascript函数validateCityInfoForm():

function validateCityInfoForm() {

                    var xmlhttp;
                    if (window.XMLHttpRequest)
                    {// code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    }
                    else
                    {// code for IE6, IE5
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlhttp.onreadystatechange = function()
                    {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                        {


                            if (xmlhttp.responseText == "true") {
                                document.getElementById("checkIfCityExistsWarning").style.display = "block";
                                document.getElementById("checkIfCityExistsWarning").innerHTML = "This city already exists!";
                                return false;
                            }
                        }
                    }
                    xmlhttp.open("GET", "checkIfCityExists.php?city=" + cityInput + "&country=" + countryInput, true);
                    xmlhttp.send();




} 

checkIfCityExists.php如果城市已存在于数据库中,则回显“true”,否则回显“假”。

问题是它总是在数据库中添加城市,即使城市已经存在。 checkIfCityExists.php返回“true”,但似乎并不重要。

我真的不知道问题是什么,任何帮助都会非常感激。 谢谢!

这里是checkIfCityExists.php:

<?php
include ('database_connection.php');
$city = mysqli_real_escape_string($dbc, $_GET['city']);
$country = mysqli_real_escape_string($dbc, $_GET['country']);

//check if the city and country already exists in the database
$query_verify = "SELECT * FROM city WHERE name = '$city' AND country = '$country'";
$result_verify = mysqli_query($dbc, $query_verify);

if(mysqli_num_rows($result_verify) == 0) { //if the city does not appear in the database
    echo "false";
}
else {
    echo "true";
}

?>

2 个答案:

答案 0 :(得分:0)

问题是,你的onsubmit没有回报。 因此validateCityInfoForm()返回undefined,这不会阻止浏览器执行操作。 validateCityInfoForm()应该return false阻止浏览器提交表单。然后在onreadystatechange调用form.submit(),如有必要。

答案 1 :(得分:0)

您正在尝试进行异步调用以进行验证。当电话回来时,为时已晚,因为表格已经提交。

Tha Ajax调用不会暂停代码执行,它会使调用和其余代码发生。

你需要做什么把它分成两步,进行Ajax调用,当onreadystatechange回来时,提交表单。

相关问题