I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.
Related
Is it possible to handle requests on XWiki other way than just with submitting HTML forms ? I need to use XMLHttpRequest, but $request
simply doesn 't react to the request.
JavaScript code
function requestHandle(msg, subj) {
var recipientName = recipientsArr.pop()[0];
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
console.log('req ok');
var mailStatusTmp = "<div class=\"mailStatus\">" + recipientName + " <span class=\"glyphicon glyphicon-ok\"/></div>";
$('#mailStatusWrapper').append(mailStatusTmp);
if (recipientsArr.length > 0) {
requestHandle(msg, subj); // call requestHandle() for next recipient
} else {
return;
}
} else {
console.log('req err');
var mailStatusTmp = "<div class=\"mailStatus\">" + recipientName + " <span class=\"glyphicon glyphicon-remove\"/></div>";
$('#mailStatusWrapper').append(mailStatusTmp);
if (recipientsArr.length > 0) {
requestHandle(msg, subj); // call requestHandle() for next recipient
} else {
return;
}
}
}
};
req.open("POST", "https://wiki.intra.tieto.com/xwiki/bin/view/Sandbox/TestPage1", true);
req.send("msg=" + msg + "&subj=" + subj + "&recipientName=" + recipientName);
}
I want to use XMLHttpRequest, because the page will send data to multiple receivers and I need to check the status every request.
If the page making the request is not on the same domain as the XWiki instance, then you might have to configure the target domain to accept cross-origin requests. That's not easy to do on XWiki's side, since there's no mechanism for responding to OPTION requests, but it's easy to configure if you're using a frontend, such as Apache HTTPD or nginx, or in the servlet container's configuration, for example in Tomcat or Jetty.
I'm trying to complete a connection using Long Polling, where the browser sends a request to the server and to be awaiting a response. To prevent this door is infinitely open, I created a routine that every 10 seconds the server sends an empty response to the browser, stating that there was nothing yet.
It's all working perfectly, had no problems related to that.
My problem is that when the user clicks on a link on the page, the browser waits for the answer call for power upgrade, or can take up to 10-sec. This makes it appear that the tool is slow.
Does anyone have any idea how to solve this?
Image:
Image:
Follows the JavaScript function used to make the call:
function loadJSON() {
if(libera) {
var data_file = http + "bibliotecas/longpolling/notificacoes.php";
var data = {};
data.n = long_n;
data.u = userchat;
data.m = msgchat;
data.c = chatUsuario;
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200) {
try {
var jsonObj = JSON.parse(http_request.responseText);
var qtd = jsonObj.funcao.length;
if(qtd > 0) {
var funcao = "";
for(var key in jsonObj.funcao) {
funcao = jsonObj.funcao[key];
MontarFuncao(eval(funcao),jsonObj.metodo[key]);
}
}
}
catch (e) {
//alert('Erro - '+ http_request.responseText);
}
loadJSON();
}
}
var string = JSON.stringify(data);
http_request.open("POST", data_file, true);
http_request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
http_request.setRequestHeader("Content-length", string.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(string);
return;
}
}
Follows the PHP function responsible for staying open expecting some changes in the database:
ob_start();
$json = json_decode(file_get_contents(`php://input`));
while($x < 5) {
if(time() >= (15 + $_SERVER['REQUEST_TIME']) || connection_aborted()) {
echo str_pad(NULL,1);
die(json_encode(array()));
flush();
ob_flush();
break;
}
//Query DB
if(count($retorno) > 0) {
flush();
ob_flush();
echo json_encode($retorno);
exit;
}
else {
flush();
sleep(2);
$x++;
}
}
I have my JavaScript function which does XMLHttpRequest. Here is my code.
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
Now, the above code works perfectly and returns 200 on POST. But I want it to return custom message on the UI based on the value posted.
If the value POSTed is less than the value in the database, I want it to give "Enter Valid number" or something like this.
I am quiet new to XMLHttpRequest . I do not know how to achieve that. Any help would be highly appreciated.
Instead of statusDisplay.innerHTML = 'Saved!'; have you considered:
statusDisplay.innerHTML = xhr.responseText;
If you do this, then your statusDisplay will be equal to whatever your post.php echos out.
For example, in post.php
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";
I have the following code:
function add_post() {
if (document.getElementById("blogTitle").value.trim() == "") {
alert("Please Insert Blog Title");
return;
}
if(CKEDITOR.instances.editor1.getData() == "") {
alert("Please Insert Blog Details");
return;
}
var data = new FormData(document.getElementById("file_add"));
var xhr = new XMLHttpRequest();
var de=CKEDITOR.instances.editor1.getData();
xhr.open("POST", "upload.php", false)
xhr.send(data + "&de=" + de);
if (xhr.status == 200) {
alert(xhr.responseText);
if(xhr.responseText == 2) {
document.getElementById("res").innerHTML="Please Upload The File";
}
if(xhr.responseText == 1) {
document.getElementById("res").innerHTML="Blog Created";
document.getElementById("blogTitle").value="";
document.getElementById("editor1").value="";
}
}
else {
output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />";
}
}
I am using CKEDITOR in textarea to get formated text. I use CKEDITOR.instances.editor1.getData() to get the textarea value. On other hand I have used FormData because I want to upload form and file using ajax. I tried to send data but the data couldn't be sent. I have stored textarea value in de variable.
Your form data object is not a string. You can't just concatenate more data into it with +.
Replace:
xhr.send(data+"&de="+de);
with
data.append("de", de);
xhr.send(data);
This is a very strange issue. The Javascript IS calling the PHP script, and the PHP script IS returning "something" (it returns array ()). The issue is, when I try to get the value of the posted data via $_POST['ID'] it basically says that there is no posted value, even though sendData does contain a value for ID. The full string of sendData (obtained through alert(sendData)) is as follows:
ID='1'&Invoice=''&FirstName=''&LastName=''&Description=''&Testimonial=''&ScreenRoom='false'&GlassWindow='true'
Javascript File: admin.js
function saveChanges() {
var sendData='ID=\'' + document.getElementById("ID").value + '\'';
sendData+='&Invoice=\'' + document.getElementById("Invoice").value + '\'';
sendData+='&FirstName=\'' + document.getElementById("FirstName").value + '\'';
sendData+='&LastName=\'' + document.getElementById("LastName").value + '\'';
sendData+='&Description=\'' + document.getElementById("Description").value + '\'';
sendData+='&Testimonial=\'' + document.getElementById("Testimonial").value + '\'';
sendData+='&ScreenRoom=\'' + document.getElementById("ScreenRoom").checked + '\'';
sendData+='&GlassWindow=\'' + document.getElementById("GlassWindow").checked + '\'';
var req = new XMLHttpRequest();
req.open("POST","scripts/saveChanges.php",true); //true indicates ASYNCHRONOUS
req.send(sendData);
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
}
PHP File (that is being posted to): saveChanges.php (located in /scripts/)
<?php
session_start();
if (!isset($_SESSION['group']) || $_SESSION['group'] != 'admin') {
die ('You do not have permission to access this page!');
}
print_r($_POST);
$ID=$_POST['ID'];
$Invoice=$_POST['Invoice'];
$FirstName=$_POST['FirstName'];
$LastName=$_POST['LastName'];
$Description=$_POST['Description'];
$Testimonial=$_POST['Testimonial'];
$Date=$_POST['Date'];
$GlassWindow=$_POST['GlassWindow'];
$ScreenRoom=$_POST['ScreenRoom'];
?>
I normally only come here in a state of desperation, and being I've spent about 3 hours now working on trying to figure this out, I consider myself fairly desperate. Any help would be greatly appreciated and please ask if you need more information.
You have to set the content type for php to read the variables
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Remove the quotes from the posted data and properly encode it
var sendData='ID=' + encodeURIComponent(document.getElementById("ID").value);
sendData+='&Invoice=' + encodeURIComponent(document.getElementById("Invoice").value);
sendData+='&FirstName=' + encodeURIComponent(document.getElementById("FirstName").value);
sendData+='&LastName=' + encodeURIComponent(document.getElementById("LastName").value);
sendData+='&Description=' + encodeURIComponent(document.getElementById("Description").value);
sendData+='&Testimonial=' + encodeURIComponent(document.getElementById("Testimonial").value);
sendData+='&ScreenRoom=' + document.getElementById("ScreenRoom").checked;
sendData+='&GlassWindow=' + document.getElementById("GlassWindow").checked;
Set the ready state listener before you send the request
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
req.send(sendData);
Try to set HTTP header:
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");