I have tried and tested various methods for completing this task for about a day now. Please be forewarned that I am building this simply, and then working my way up!
I have a form that consists of a textarea, and two input fields. The input fields allow a XMLHttpRequest
to send information pertaining to a username, and message - sent to a chatroom that I am trying to make.
The problem that I have with my request, is simply that I can send the information, and insert a row into a database, but I can't get any information back! You will see from the code below, that I have put an alert in, to check what the response text is, but it comes back as null (not undefined
, but ""
). Please check the code below:
function insertMessage() {
var username = document.getElementById('username').value;
var message = document.getElementById('message').value;
var queryString = "username=" + username + "&message=" + message;
// send the username and message information to be inserted into the database
var url = 'classes/chatroom/chatroom.upload.php';
// create xml request
var request = createCORSRequest("POST", url)
// create a function that will receive data sent from the server
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(queryString);
}
function createRequest(method, url) {
var thisRequest = new XMLHttpRequest();
if ("withCredentials" in thisRequest) {
// thisRequest has 'withCredentials' property only if it supports CORS
thisRequest.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
thisRequest = new XDomainRequest();
thisRequest.open(method, url);
} else {
thisRequest = null;
}
return thisRequest;
}
The code that pertains to the insertion of a database row is:
<?php
include 'chatroom.config.inc.php'; // the database file
$message_username = $_POST['username'];
$message_content = $_POST['message'];
if ($message_username == "Username: Once entered, you don't have to enter again" || $message_username == "") {
$message_username = "Guest";
}
if ($message_content == "Message:" || $message_content == "") {}
else {
$users->post_message($message_username, $message_content); // insert database row using PDO query
}
?>
Could anyone provide a clue as to where I'm going wrong?