通过ajax post将get变量传递给php

时间:2015-06-07 16:39:22

标签: javascript php jquery mysql ajax

我有3个文件:我的主页chatterFront.php,然后我的js ajax文件chatterScript.js和获取并发送消息的php脚本chatterEngine.php。如何定义变量并将其从chatterFront.php传递给chatterEngine.php。我无法改变ajax post方法。我也希望它是安全的(服务器端)。

基本上它是一个$ _GET变量我想从chatterFront.php?CID = 1传递到chatterEngine.php。它与全局变量有关吗?

我想在发送和检索消息时使用该变量

chatterFront.php(聊天的前面的html)

<!DOCTYPE HTML>
<html>
<head>
<title>Test Chatting System</title>
<link href="chatterStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="chatterScript.js"></script>
</head>
<body>


<ul id="chatMessageList" class="chatMessageList"></ul>

<form action="chatterEngine.php" method="post" id="formPostChat">
    <fieldset>
        <input type="text" id="postCID" name="postCID" value="1">
    </fieldset>
    <fieldset>
        <input type="text" id="postText">
    </fieldset>
    <fieldset>
        <input type="submit" value="Reply" />
        <span class="errorMessage" id="postError"></span>
    </fieldset>
</form>

chatterEngine.php(ajax调用的php文件)

<?php
    class Chatter{
        //change this according to your database setup
        protected $server = 'localhost';
        protected $username = 'hidden';
        protected $password = 'hidden';
        protected $database = 'hidden';
        //leave this as our database connection later
        protected $connection = null;

        public function __construct(){
            $this->connection = @mysql_connect($this->server, $this->username, $this->password);
            if($this->connection){
                if(!mysql_select_db($this->database)) die('database not found');
            }
            else die('database connection failed. Check your setup');

            $mode = $this->fetch('mode');

            switch($mode){
                case 'get':
                    $this->getMessage();
                    break;
                case 'post':
                    $this->postMessage();
                    break;
                default:
                    $this->output(false, 'Wrong mode.');
                    break;
            }

            return;
        }

        protected function getMessage(){
            $endtime = time() + 20;
            $lasttime = $this->fetch('lastTime');
            $postCID = ; // Set this variable in chatterFront.php
            $curtime = null;

            while(time() <= $endtime){
                $rs = mysql_query("
                    SELECT *
                    FROM conversation_reply
                    WHERE c_id_fk = $postCID
                    ORDER BY time desc
                    LIMIT 0, 30
                ");

                if($rs){
                    $messages = array();

                    while($row = mysql_fetch_array($rs)){
                        $messages[] = array(
                            'user' => $row['user_id_fk'],
                            'text' => $row['reply'],
                            'time' => $row['time']
                        );
                    }

                    $curtime = strtotime($messages[0]['time']);
                }

                if(!empty($messages) && $curtime != $lasttime){
                    $this->output(true, '', array_reverse($messages), $curtime);
                    break;
                }
                else{
                    sleep(1);
                }
            }
        }

        protected function postMessage(){
            $user = $this->fetch('user');
            $text = $this->fetch('text');

            if(empty($text)){
                $this->output(false, 'Username and Chat Text must be inputted.');
            }
            else{
                $userid = 1;
                $conversationid = 1;
                $ip = $_SERVER['REMOTE_ADDR'];              
                $rs = mysql_query("
                    INSERT INTO conversation_reply(                     
                        reply,
                        user_id_fk,
                        ip,
                        time,
                        c_id_fk
                    )
                    VALUES(
                        '$text',
                        '$user',
                        '$ip',
                        CURRENT_TIMESTAMP,
                        '$conversationid'
                    )
                ");

                if($rs){
                    $this->output(true, '');
                }
                else{
                    $this->output(false, 'Chat posting failed. Please try again.');
                }
            }
        }

        protected function fetch($name){
            $val = isset($_POST[$name]) ? $_POST[$name] : '';
            return mysql_real_escape_string($val, $this->connection);
        }

        protected function output($result, $output, $message = null, $latest = null){
            echo json_encode(array(
                'result' => $result,
                'message' => $message,
                'output' => $output,
                'latest' => $latest
            ));
        }
    }

    new Chatter();

chatterScript.js(The ajax)

    function Chatter(){
    this.getMessage = function(callback, lastTime){
        var t = this;
        var latest = null;

        $.ajax({
            'url': 'chatterEngine.php',
            'type': 'post',
            'dataType': 'json',
            'data': {
                'mode': 'get',
                'lastTime': lastTime,
            },
            'timeout': 30000,
            'cache': false,
            'success': function(result){
                if(result.result){
                    callback(result.message);
                    latest = result.latest;
                }   
            },
            'error': function(e){
                console.log(e);
            },
            'complete': function(){
                t.getMessage(callback, latest);
            }
        });
    };

    this.postMessage = function(user, text, callback){
        $.ajax({
            'url': 'chatterEngine.php',
            'type': 'post',
            'dataType': 'json',
            'data': {
                'mode': 'post',
                'user': user,
                'text': text
            },
            'success': function(result){
                callback(result);
            },
            'error': function(e){
                console.log(e);
            }
        });
    };
};

var c = new Chatter();

$(document).ready(function(){
    $('#formPostChat').submit(function(e){
        e.preventDefault();

        var user = $('#postUsername');
        var text = $('#postText');
        var err = $('#postError');

        c.postMessage(user.val(), text.val(), function(result){
            if(result){
                text.val('');
            }
            err.html(result.output);
        });

        return false;
    });

    c.getMessage(function(message){
        var chat = $('#chatMessageList').empty();

        for(var i = 0; i < message.length; i++){
            chat.append(
                '<li class="chatMessage">' +
                '       <span class="chatUsername">' + message[i].user + '</span>' +
                '       <p class="chatText">' + message[i].text + '</p>' +
                '</li>'
            );
        }

        $('#chatMessageList').scrollTop($('#chatMessageList')[0].scrollHeight);
    });
});

我已经设置了所有的数据库,并且我确实使用会话变量使其工作但是效果非常慢(出于某种原因 - 可能是因为我把它们放在哪里 - 可能导致循环)

0 个答案:

没有答案