I'm creating a shoutbox based on php, mysql and ajax for my website. Now I want the user to be able to write a message, open the saving file using Ajax and insert the message to the database with php. Everything is working fine - except for the ajax part. Somehow it doesn't open the saving file.
html:
<input type='text' id='shoutbox-comment' name='shoutbox-msg' style='width: 179px;' value='My message'>
<input type='submit' name='shoutbox-submit' value='ok' onclick='shoutbox-send();'>
I'm using the framework Medoo for any database request. I've tried the code using a normal html form and the file itself is working fine.
php "shoutbox-write.php":
if (!empty($_POST['msg'])){
$userid = $_SESSION['id'];
$message = substr($_POST['msg'],0,200);
$message = xss($message);
$now = time();
$database->insert("shoutbox", ["userid" => $userid, "message" => $message, "time" => $now]);
}
Now comes the problem part. I've tried various things, I even changed the whole script to GET to see if it's working. Nothing works. The first javascript code is one I took from here. The second one is the one I used before. Both are not working though. Please note that I want to solve this without using JQuery.
function shoutbox-send() {
var xmlHttp = new XMLHttpRequest();
var url="<?php echo PATH; ?>divers/shoutbox-write.php";
var message = document.getElementById('shoutbox-comment').value;
var parameters = "msg="+message;
xmlHttp.open("POST", url, true);
//Black magic paragraph
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById('shoutbox-comment').value="";
}
}
xmlHttp.send(parameters);
}
function shoutbox-send() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var message = document.getElementById('shoutbox-comment').value;
document.getElementById('shoutbox-comment').value = "";
}
};
xhttp.open("POST", "<?php echo PATH; ?>divers/shoutbox-write.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("msg=" + message + "");
}
I'd appreciate your help.
Edit: Solved! Function names must not contain hyphens. It's working now