Ajax - php echo语句不起作用

时间:2015-09-26 10:46:41

标签: javascript php mysql ajax

我正在开发一个ajax-php事件日历,并在表单中添加事件我有ajax:

function PostData() {

                var xhr;
                if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                }
                else if (window.ActiveXObject) {
                    xhr = new ActiveXObject("Msxml2.XMLHTTP");
                }
                else {
                    throw new Error("Ajax is not supported by this browser");
                }
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200 ){//&& xhr.status < 300) {
                            if(xhr.responseText == 1){
                                document.getElementById('div1').innerHTML = "SUCCESS";
                               //window.location = "form2.php";
                            }
                            else{
                                document.getElementById('div1').innerHTML = xhr.responseText;
                            }
                        }
                    }
                }
                var a = document.getElementById("aaa").value;
                var b = document.getElementById("bbb").value;
                var c = document.getElementById("ccc").value;

                xhr.open('POST', 'addEvent.php');
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send("xxx=" + a+"&yyy="+b+"&zzz="+c);
}
        </script>`:

和我的服务器端php代码应该回应添加事件的结果,例如成功或数据库错误等:

  <?php
include ("connect.php");
$eventDate = $_POST["xxx"];
$eventTime = $_POST["yyy"];
$eventDesc = $_POST["zzz"];

if($eventDate != '' && $eventDesc != '' && $eventTime != ''){
   // $timestamp = strtotime($eventTime);
    //$eventTime =  date("H:i", $timestamp);

    $sql = "INSERT INTO events(evdate,evtime,evdesc,username) VALUES ('$eventDate','$eventTime','$eventDesc','usr')";

    if(mysqli_query($conn, $sql)) 
        echo 1;
    else 
        echo mysqli_error();
}
else
    echo 'you must not leave it blank';

mysqli_close($conn);

?>

作为输出,如果在事件添加表单中有未填充的字段,则php文件底部的echo语句有效。但是如果插入了一行,则echo语句不起作用。此外,如果插入记录时出错,仍然无效。

1 个答案:

答案 0 :(得分:0)

if(mysqli_query($conn, $sql)) 
    echo 1;
else 
    echo mysqli_error($conn); // required connection parameter here...