简体   繁体   中英

AJAX chat system not working

I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.

Here is the Javascript (On same page as html)

Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.

<script type="text/javascript">
    function SendText() {
        if (document.getElementById("Text").innerHTML == "") {
            return;
        } else
        {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
                }
            }
            Text = document.getElementById("Text").value;
            xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
            xmlhttp.send();
        }
    }
</script>

Here is the HTML (Same page as the script)

<div>
    <p>
        <span id="DisplayText">
            TEXT GOES HERE
        </span>
    </p>
</div>
<form action="" onsubmit="SendText();">
    <input type="" name="" id="Text" />
    <input type="submit" value="Send" name="Send" />
</form>

The PHP code is here

<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
    echo "Database exists";
    doSomething();
} else {
    echo "Database does not exist";
    mysqli_query($Connection, $Create);
    doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
    // Get the sent chat
    $Input = $_REQUEST["Chat"];
    // Insert into the database the new chat sent
    mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
    // Select everything from the database
    $Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
    // Display everything from the database in an orderly fashion
    // --
    // For the length of the database
    // Append to a variable the next table row
    // --
    while ($Row = $Result->fetch_array()) {
        // Make Variable accessable
        global $Input;
        // Append username to the return value
        $Input = $Input . $Row["Username"] . " : ";
        // Append chat to the return value
        $Input = $Input . $Row["Chat"] . "<br />";
    }
}
// Will return the value
echo $Input;
?>

My connection to the Database is fine. I'm using it on other pages that work. So lets assume that's not the problem. :P

Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for. I'm new to AJAX.

You do a wrong test with

if (document.getElementById("Text").innerHTML == "")

It should be the same way you use to get the text for sending in the AJAX

if (document.getElementById("Text").value == "")

So check its value property and not its innerHTML as input elements do not have html content..


Be careful though because your code is wide-open to SQL injection attacks .

Try AJAX Long Polling technique for chat application. Here is example

http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax

1st : use input's value property instead innerHTML

eg. use

if (document.getElementById("Text").value == "")

instead of

if (document.getElementById("Text").innerHTML == "")

2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,

eg. use

onsubmit="SendText(); return false;"

instead of just

onsubmit="SendText();"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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