Long Polling in GO, Server Not Responding Appropriately? - javascript

I am trying to implement a simple "global" counter that updates based on every user that clicks the button on their browsers button. For example, if you go to the website and click the button, I will see the counter increase on my side if I'm on the same website. I sought to do this with long polling, but am facing some issues. Mainly the server variable is not coming back as I think it should.
The server:
package main
import (
"net/http"
"log"
"io"
"io/ioutil"
)
var messages chan string = make(chan string, 100)
var counter = 0
func PushHandler(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(400)
}
counter += 1
messages <- string(counter)
}
func PollResponse(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, <-messages)
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/poll", PollResponse)
http.HandleFunc("/push", PushHandler)
err := http.ListenAndServe(":8005", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
The client:
<html>
<script language=javascript>
function longpoll(url, callback) {
var req = new XMLHttpRequest ();
req.open ('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
callback(req.responseText);
longpoll(url, callback);
} else {
alert ("long-poll connection lost");
}
}
};
req.send(null);
}
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
function send() {
var box = document.getElementById("counter");
var req = new XMLHttpRequest ();
req.open ('POST', "/push?rcpt=", true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
} else {
alert ("failed to send!");
}
}
};
req.send("hi")
//box.innerHTML += "test" ;
}
</script>
<body onload="longpoll('/poll', recv);">
<h1> Long-Poll Chat Demo </h1>
<p id="counter"></p>
<button onclick="send()" id="test">Test Button</button>
</body>
</html>
The counter variable is not coming back from the server for some reason. I believe I am changing the state every time the button is clicked and so the longpolling function should get the newly updated counter variable. If you have any suggestions, please let me know!

I see two issues in you program:
1. In the server:
messages <- string(counter)
You should use "strconv" package
messages <- strconv.Itoa(counter)
string(0) will return something like []byte{0} not a "0"
2. In your client:
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
Should be:
function recv(msg) {
var box = document.getElementById("counter");
box.innerHTML += msg + "\n";
}
I don't think the p element have value property

Related

handle servlet custom exception in javascript and showing error page in jsp

Am throwing exception from my servlet and in the eclipse console its printing the exception logs whenever exception is occured. But am trying to show that exception in JSP pages that am not getting.
Please find my code below.
code to pass the request :
function sendRequest( functionCallback, servletLocation, queryString)
{
var asyncRequest = newXMLRequest();
// Set the handler function to receive callback notifications from the request object
var handleResponse = getReadyStateHandler(asyncRequest, functionCallback);
asyncRequest.onreadystatechange = handleResponse;
// Send a POST to servlet for information. Third parameter specifies request is asynchronous.
asyncRequest.open("POST", servletLocation, true);
asyncRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
asyncRequest.send(queryString);
if ( document.getElementById("filterMessage") != null )
{
document.getElementById("filterMessage").innerHTML = "<span class = 'red'>Filtering...Please Wait</span>";
}
}
code to handle the respose :
function getReadyStateHandler(req, responseXmlHandler)
{
// Return an anonymous function that listens to the
// XMLHttpRequest instance
return function ()
{
// If the request's status is "complete"
if (req.readyState == 4)
{
// Check that a successful server response was received
if (req.status == 200)
{
// Pass the XML payload of the response to the
// handler function
responseXmlHandler(req.responseXML);
}
else
{
// An HTTP problem has occurred
alert("HTTP error: " + req.status);
}
}
}
}
function reloadPage() {
window.location.reload(true);
}
invoking servlet call from the below code.
function updateProgramVersion(e) {
var washoutIdStr = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.sparWashoutId.children.washoutItem.value;
var programVersionStr = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersionModify.children.programVersion.value;
var sparNumber = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.sparNumber.children.sparNumber.value
if( (e.target || e.srcElement ).id == 'programVersionUpdatebtn') {
query = 'actionId=updateProgramVersion&washoutIdStr='+washoutIdStr+"&programVersion="+ programVersionStr+"&sparNumber="+sparNumber;
servlet = "<%=UrlBuilder.getServletRoot() + ApplicationConstants.SERVLET_REPORT_SPAR%>"; method="POST";
sendRequest(reloadPage, servlet, query); // servlet call
(e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersion.style.display = 'none';
(e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersionTD.style.display = 'block';
}
}
Please find my below servlet code :
else if(actionId.equals("updateProgramVersion")) {
updateProgramVersion(washoutId, sparNumber, programVersion);
//nextPage = mappings.findForward("display");
}
private void updateProgramVersion(String washoutId, String sparNumber, String programVersion) throws ApplicationException{
boolean isExist = sparwashoutService.getProgramVersion(washoutId, sparNumber, programVersion);
if(isExist) {
sparwashoutService.updateProgramVersion(washoutId, sparNumber, programVersion);
} else {
throw new InvalidInputException("Version number is not valid","Version number is not valid",this.getClass().toString().substring( getClass().toString().lastIndexOf(".") + 1 ) + ".performTask()");
}
}
You need to send back custom message which you need to show in jsp via servlet using response.getWriter().write().. also you can set status so that it will not enter inside if (req.status == 200) {... Here is example with try-catch block modify below code according to your requirement .
Servlet Code :
try
{
//check some condition
response.setContentType ("text/xml");
response.setCharacterEncoding ("UTF-8");
response.setStatus(200); //set status
response.getWriter().write(yourxmldata); //send message
}
//handling the exception
catch (Exception e)
{
response.setContentType ("text/plain");//set contenttype to text
response.setCharacterEncoding ("UTF-8");
response.setStatus(406); //set status
response.getWriter().write (e.getMessage () + "I AM IN EXECPETION"); //get your execption message
}
and in Ajax just check the status code :
if (req.status == 200) {
responseXmlHandler(req.responseXML);//xml return
} else if(req.status == 406){
alert(req.responseText);//text return
}

Response.write() or .toString() (bug?) on NodeJS server

I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.

Getting data from python in Javascript and AJAX

I have some issues retrieving info from python and try to show the data in a html page
I get the date from a python script (data.py)
import cx_Oracle
import json
lst_proveedores=[{}]
conn_str = 'user/pass#database'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute('select id, name from provider')
for row in c:
record1 = {"id":row[0], "name":row[1]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I try to parse the info with AJAX in a html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov1.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += data[obj].id+" is "+data[obj].nombre+"<hr />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
but doesn't work
I setup apache to execute python scripts and work with very simple scripts, but doesn't work when I retrieve data from the database
How can I show the data in a html page?
Or what language or framework may I can use to show the data
Any advice
I am desperate
Thanks in advance
First of all, you should try visit your python files in browser. If you can't see json print on page, there're problems in your server or python code.
If it works, that may be something wrong in your Ajax request.
You can use jQuery or zepto.js to help. They contain a method of Ajax: $.ajax.
You can visit: http://zeptojs.com
And search "$.ajax" on the page for help; )
===============================================================
try this:
//var data = JSON.parse(hr.responseText);
var data = JSON.parse(hr.response);
===============================================================
and this is my onreadystatechange function code, use it if it helps:
ajaxObject.onreadystatechange = function(){
//console.info('[Ajax request process] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (ajaxObject.readyState == 4 && ((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
var result = null;
switch (dataType){
case 'text':
result = ajaxObject.responseText;
break;
case 'xml':
result = ajaxObject.responseXML;
break;
case 'json':
default:
result = ajaxObject.response ? JSON.parse(ajaxObject.response) : null;
break;
}
if (typeof(success) == 'function'){
success(result,url);
}
}else if (ajaxObject.readyState > 1 && !((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
console.warn('[Ajax request fail] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (typeof(error) === 'function' && errorCallbackCount == 0){error(url);errorCallbackCount++;}
return false;
}
}

Calculating big task with response for each executed step

Sorry if this topic already exists, but I couldn't find the solution. I have some calculations processed on server side. These calculations consists of several steps. I would like a response for each executed step. For instance, there are 5 steps in a task, and server must send me 5 responses:
Step 1 is executed
Step 2 is executed
Step 3 is executed
...etc
I read a lot of forums and blogs, but I can't solve this problem. In my case I think it is better to use long polling in comet. I wrote a simple example of my task (posted below); it doesn't work. This task has button which starts the counter (from 1 to 11 with sleep 1 sec), then Ajax sends a requests. The server must give the accumulated text ($q_msg), clear this variable, and continue to accumulate another counts. But instead of this, server accumulates everything without any responses and at the end response all in an answer. So, where is my fault? Please, assist me.
HTML:
<script type="text/javascript">
var request;
function createXMLRequest() {
request = new XMLHttpRequest();
return request;
}
//start counter
function comet_btnStart() {
document.getElementById('count1').innerHTML = "";
createXMLRequest();
var param = "btnStart=pusk";
request.open("GET", "counter.php?" + param, true);
request.onreadystatechange = comet_response;
request.send(null);
}
//get values
var q = "";
function comet() {
createXMLRequest();
var param = "q=" + q;
request.open("GET", "counter.php?" + param, true);
request.onreadystatechange = comet_response;
request.send(null);
}
function comet_response() {
if (request.readyState === 4)
{
if (request.status === 200)
{
if (request.responseText !== null)
{
var text = request.responseText;
if (text === "end") document.getElementById('count1').innerHTML += "<br/>Task is executed";
else
{
var result = text.split(",");
q = result[result.length-1];
document.getElementById('count1').innerHTML += "<br/>" + request.responseText;
setTimeout(comet, 2000);
}
}
else document.getElementById('count1').innerHTML += "<br/>No response";
}
else document.getElementById('count1').innerHTML += "<br/>Invalid connection";
}
}
</script>
</head>
<body>
<div>
Click button to start counter: <input type="button" value="Начать" name="btnStart" id="btnStart" onclick="comet_btnStart()" /><br/><br/>
Counts:<br/> <span id='count1' style='color: #246499; font-weight: bold'></span>
</div>
</body>
PHP:
<?php
if (isset($_GET['btnStart']))
{
$q_msg = "";
$q = 0;
logic::counter();
echo $q_msg;
$q_msg = "";
}
if (isset($_GET['q']))
{
$lastq = $_GET['q'];
global $q;
if ($lastq < $q)
{
echo $q_msg;
$q_msg = "";
}
else echo "end";
}
class logic
{
static function counter()
{
global $q;
while ($q <= 10)
{
sleep(1);
$q++;
global $q_msg;
if (strlen($q_msg) > 0) $q_msg .= ", " . $q;
else $q_msg = $q;
//just for debugging
echo $q_msg; //why server doesn't send data???
}
}
}
$msc=microtime(true);
//executing code
$msc=microtime(true)-$msc;
echo $msc.' seconds'; // in seconds
echo ($msc*1000).' milliseconds'; // in millseconds
i dont know if this is what you are looking for. But if i understsand correct this is what you are looking for. You can read more here How to get the execution time of a MySQL query from PHP?
Credit to Christian

XMLRequest ResponseText is blank

I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started

Categories

Resources