Ajax自动刷新 - PHP变量未正确传递到自动刷新功能

时间:2015-12-31 09:32:51

标签: php ajax refresh

我正在使用Eliza Witkowska的Ajax自动刷新代码:http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii

我已经修改了代码,所以我可以从url传递变量。除了一行代码之外,一切都很好。代码行是检查新记录的数据库查询的一部分。当我尝试将变量传递给查询时,自动刷新停止工作(所有其他功能继续工作)。如果我使用静态值,它可以正常工作。

静态值(这可行)

    $result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID=3 AND UserID=25');

带变量(这不起作用)

    $result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');

将变量传递到同一脚本中的另一个函数没有问题。所以我被困住了几天。任何帮助,不胜感激。

db.php中

class db{

/**
 * db
 *
 * @var $   public $db;
 */
public $db;

function __construct(){
    $this->db_connect('###SERVER###','###USERNAME###','###PASSWORD###','###DATABASE###');   //my database information
}

function db_connect($host,$user,$pass,$database){
    $this->db = new mysqli($host, $user, $pass, $database);

    if($this->db->connect_errno > 0){
        die('Unable to connect to database [' . $this->db->connect_error . ']');
    }
}

//////////////////////////////
//This is the function that is having an issue when I pass it variables
//////////////////////////////

function check_changes(){
    global $UserID;     //Declaring my variable
    global $AgentID;    //Declaring my variable
    $result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');

    if($result = $result->fetch_object()){
        return $result->counting;
    }
    return 0;
}


//////////////////////////////
//This function has no problem, even when I pass it variables
//////////////////////////////
function get_news(){
    global $UserID;
    global $AgentID;
    if($result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50')){
        $return = '';
        while($r = $result->fetch_object()){
            if ($r->ChatType==1) {      //ChatType is a field in the table that distinguishes Agent texts from User Texts
                $return .= ''.htmlspecialchars($r->title).'';
            } else {
                $return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
            }
        }
        return $return;
    }
}


}

以下是其他文件:

的index.php

<?php
$AgentID = $_REQUEST["AgentID"];  //Grabing AgentID from the URL
$UserID = $_REQUEST["UserID"];    //Grabing UserID from the URL
require('common.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
    /* AJAX request to checker */
    function check(){
        $.ajax({
            type: 'POST',
            url: 'checker.php?AgentID=<? echo $AgentID; ?>&UserID=<? echo $UserID; ?>',  //This line has been updated by passing parameters
            dataType: 'json',
            data: {
                counter:$('#message-list').data('counter')
            }
        }).done(function( response ) {
            /* update counter */
            $('#message-list').data('counter',response.current);
            /* check if with response we got a new update */
            if(response.update==true){
                $('#message-list').html(response.news);
                var audio = new Audio('img/solemn.mp3');
                audio.play();
            }
        });
    }
    //Every 2 sec check if there is new update
    setInterval(check,2000);
</script>
<style>
body {
    margin:0px;
    padding:0px;
    vertical-align:top;
}
</style>
</head>
<body>
<?php /* Our message container. data-counter should contain initial value of counter from database */ ?>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
    <?php echo $db->get_news();?>
</div>
</body>
</html>

checker.php

<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
$AgentID = $_REQUEST["AgentID"];  //passing my variable to db.php
$UserID = $_REQUEST["UserID"];    //passing my variable to db.php
$data['news'] = $db->get_news();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
?>

的common.php

<?php
require_once ('db.php'); //get our database class
$db = new db();
/* end of file common.php */
?>

1 个答案:

答案 0 :(得分:1)

我认为问题是在checker.php中包含数据库连接时变量不可用〜声明变量然后包含数据库连接。

另外,我建议不要使用global表达式来定义db类方法中的变量,而是将它们作为参数传递给它们。我希望以下可能有用 - 但它没有经过测试。这种在sql中使用变量的方法有或者应该是关注的 - 它容易受到可怕的sql injection的影响〜更好的方法是在db类中使用prepared statements并绑定{{1} }和$agentID使用$UserID方法。

bind_param()