Javascript not working when accessing from remote computer - javascript

I accessed my client page using this link
http://XX.XX.XX.XX/project/client.php
.It has few lines of javascript and html but its not working at all . But when i access my client page using this link
http://localhost/project/client.php
, it works. I know something i should change in javascript code but i dont know what . So please tell me . Here is my client code :
<html>
<head>
<style>
#chatlog {width:440px; height:200px; border:1px solid;overflow:auto;}
#userslog {width:440px; height:200px; border:1px solid;overflow:auto;}
#msg {width:330px; height:100px;}
</style>
<script>
function initialize(){
var host = "ws://localhost:12345/project/server3z.php";
try{
socket = new WebSocket(host);
chatlog('WebSocket - status '+socket.readyState);
socket.onopen = function(event){chatlog("WebSocket status "+this.readyState); };
socket.onmessage = function(event){ chatlog(event.data); };
socket.onclose = function(){ chatlog("WebSocket status "+this.readyState); };
socket.onerror = function(event){chatlog("Error :"+event.data); };
}
catch(err){ chatlog(err); }
}
function send()
{
var chat;
chat= document.getElementById("msg").value;
if(!chat){ alert("Message can not be empty"); return; }
try{ socket.send(chat); chatlog('Sent: '+chat); } catch(err){ log(err); }
document.getElementById("msg").value = "";
}
function quit(){
chatlog("closed!");
socket.close();
chatlog("WebSocket status "+socket.readyState);
}
function chatlog(msg)
{
var match=msg.match(/10101010101010/g);
if(match)
{
var msg=msg.split("10101010101010");
document.getElementById("userslog").innerHTML+="<br>"+msg[0];
}
else
{
document.getElementById("chatlog").innerHTML+="<br>"+msg;
}
}
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
</head>
<body onload="initialize()">
<center>
<div id="chatlog"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send</button>
<button onclick="quit()">Stop</button>
<div id="userslog"></div>
</center>
</body>
</html>

Don't hard-code the host to localhost, use location.hostname instead:
var host = "ws://" + location.hostname + ":12345/project/server3z.php";

You are using WebSocket are you sure that your browser in the other PC it's supports HTML5 and WebsoCKET?
WebSocket was introduced early

this line i sthe problem var host = "ws://localhost:12345/project/server3z.php";
localhost by default means your local machine. so when you access it from you local machine it maps to the correct machine but when you access it from a remote server it just searches that server because now the localhost is changed

In your code you have a hardcoded reference to a url on your local host:
var host = "ws://localhost:12345/project/server3z.php";
If you want to access it from another computer, you'll need to replace that with a domain or ip address that the remote client can resolve.

thanks for answer !! :)
madthew was right . I was using IEwhich does not support websocket. It is working in my mozila now.

Related

How to make the client receive server sent event using Javalin?

I am trying to implement a server client project which needs the server to send data to the client every 5 minutes with the client only asking in the beginning of connection. Server-sent events seem to be the go-to solution.
I have tried to use the functions given in the Javalin Documents. I am able to receive a response with a simple get from the server. But I couldn't establish a sse connection. The code enters the lambda function in the server but the client does not receive anything. I am not sure if the client or the server, or even both have a problem.
The only output we get from the codes below is "connected" on the server side. Thank you in advance.
Code for the server
import io.javalin.Javalin;
public class SimpleTwitter {
public static void main(String[] args) {
Javalin app = Javalin.create().start(7000);
app.sse("/sse", client ->{
System.out.println("connected");
client.sendEvent("message","Hello, SSE");
client.onClose(() -> System.out.println("Client disconnected"));
});
app.get("/", ctx -> ctx.result("Hello World"));
}
}
Code for the client
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("http://localhost:7000/sse");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
Turns out the problem was not the code. By looking at the developer tools on chrome, we saw the following:
"Access to resource at 'http://localhost:7000/sse' from origin 'null'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource."
When we installed a chrome extention called "Allow-Control-Allow-Origin: *", we were able to see the output.
Also, here are the updated better working codes:
> <<!DOCTYPE html> <html> <body>
>
> <h1>Tweets</h1>
>
> <script> new
> EventSource('http://localhost:7000/sse').addEventListener( "hi", msg
> =>{ document.write(msg.data); }); </script>
>
> </body> </html>
...
public static void main(String[] args) throws InterruptedException {
Queue<SseClient> clients = new ConcurrentLinkedQueue<>();
Javalin app = Javalin.create().start(7000);
app.sse("/sse", client -> {
clients.add(client);
client.onClose(() -> clients.remove(client));
});
while (true) {
for (SseClient client : clients) {
client.sendEvent("hi", "hello world");
}
TimeUnit.SECONDS.sleep(1);
}
}

Why not one method to connect and send in websocket?

I am new websocket and refering to the below Spring Websocket tutorial and it is working fine in my system. I am also using stomp.js and sockjs-0.3.4.js.
https://spring.io/guides/gs/messaging-stomp-websocket/
If the html and javascript has two distinct methods like below, it works.
function connect() {
var socket = new SockJS('/app/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
//showGreeting(greeting);
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
If I write a single javascript function as given below, it does not work and get the error as Uncaught Error: INVALID_STATE_ERR.
function startAndSend() {
connect();
sendName();
}
I want to know why it is not working. It may be dumb question, please help me in this regard. I provide below the complete html file. Is it always necessary to write html button for connect and send information to websocket as given in the Spring Websocket example ? Is it not possible to onClick of a button, it will connect and send information to websocket ? It seems to be a peculiar for me, I need your help.
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="sockjs-0.3.4.js"></script>
<script src="stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS('/app/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
//showGreeting(greeting);
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
console.log(message);
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
//Does not work
function startAndSend() {
connect();
sendName();
}
</script>
</head>
<body>
<noscript>
<h2 style="color: #ff0000">Seems your browser doesn't support
Javascript! Websocket relies on Javascript being enabled. Please
enable Javascript and reload this page!</h2>
</noscript>
<div>
Stomp Over Websocket using Spring
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
<button id="check" onclick="startAndSend();">StartAndSend</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
That is because stompClient.connect() method is asynchronous and when you call sendName() right after connect() connection is not established yet.
You are supposed to call sendName() in stompClient.connect() callback to be sure that connection is established by the time sendName() invokes.
For example:
function connect() {
var socket = new SockJS('/app/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
sendName();
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
//showGreeting(greeting);
showGreeting(JSON.parse(greeting.body).content);
});
});
}
Without being familiar with Stomp (so just a wild guess): The actual stompClient.connect call takes a callback as the second argument. This indicates that this runs asynchronous. Your attempt at using the connection then fails because it is executed before the connection has actually been established. Try what happens when you put the call into the callback of the connect function.

Receiving and sending using node.js and websockets

Client code:
<body>
<input type=text id="input">
</body>
<script>
var connection = new WebSocket('ws://chat-mmnnww123.c9users.io');
/*AFTER CONNECTION*/
$('#input').change(function(){
connection.send(this.value);
$('#input').val("");
alert("DONE");
});
connection.onmessage = function(e){
alert(e.data);
};
</script>
This code just send message write in the input to the server website.
Server code:
var ws = require("nodejs-websocket");
var server = ws.createServer(function(conn){
console.log("New Connection");
//on text function
conn.on("text", function(str){
/*
I want to send this str to agent.html page
*/
conn.sendText("Message send : " + str.toUpperCase());
});
//closing the connection
conn.on("close", function(){
console.log("connection closed");
});
}).listen(process.env.PORT, process.env.IP);
This is the server code which SHOULD take the value in str and pass it to the agent.html page.
Now all I want is to take that str value and pass it to page agent.html that I haven't created yet. This page will help the agent to see the client message.
It should be instant and without refreshing the page.

Getting basic node.js server and a client to work

Trying to implement the simplest server-client on my PC.
The argv part is because I'm debugging it in VS and it started as an application. It works as a standalone app and I want to make it a server. If I enter
http://localhost:8080/
in the browser I can see in the node.exe window that the server runs properly. But when I run the html with the script nothing happens (I get no response, although no error either, and the server doesn't get the request)
If anyone could help I would appreciate it.
Client:
<html>
<body>
<script type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>
Server:
var fs = require("fs"),
my_http = require("http"),
sys = require("sys");
my_http.createServer(function(request,response){
fs.readFile(process.argv[2], 'utf8', function(err, data) {
if (err) {
console.log("FILE READ ERROR: ", err);
process.exit();
}
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("message");
response.end();
});
}).listen(8080);
sys.puts("Server Running on 8080");
EDIT:
Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange.
The new client code:
default.htm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<h1>TypeScript HTML App</h1>
<div id="content"></div>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</body>
</html>
app.ts: (it's in js though)
var response;
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
var response;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
response.innerHTML = "hi";
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
window.onload = () => {
response = document.getElementById('content');
};
I am now getting a "Cancelled" network request in Chrome's dev tools.
New answer:
What do you get if you log some values out in your onreadystatechange handler?
ajaxRequest.onreadystatechange = function () {
console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
Original answer:
There are a couple of possibilities that might be occurring.
Your ajaxRequest variable is local to the ajaxFunction() and might be getting garbage collected after the function is executed.
Try moving the ajaxRequest outside ajaxFunction() like this:
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction() {
... rest of your client code.
}
That way the variable will still be in scope after the function has been invoked.
Alternatively, you might be running into a cross-domain security issue if your client is running on a different domain to your server (e.g. http://localhost:8081/ vs http://localhost:8080/).
Can you check if the browser is actually making the request (i.e. check with the browser's development tools and not on the server)? There should be a 'network' tab in the development tools for whichever browser you are using.
Have a look at the documentation for CORS (Cross-Origin Resource Sharing) to get an idea of what might be happening.
Edit: Here's a nice overview of cross-domain security errors and how to address it in a standard Node.js server: http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/
This answer shows how to add the headers in a Connect server:
How can I add CORS-Headers to a static connect server?

HTML page will not complete an XMLHTTPRequest

So I'm trying to get an outside script to complete a login request using XMLHTTPRequest.
The error I'm getting is XMLHttpRequest cannot load http:///.php. Origin http://* is not allowed by Access-Control-Allow-Origin.
Now I've grown quite familiar with this post:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
And from what I understand I need to request it as a JSONP object. The problem with that, is I'm using an XMLHTTPRequest and cannot use the jQuery library to do that.
Here's my code from the html page I'm trying to execute the script from:
<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script language = "javascript" type="text/javascript" src="jquery-1.7.2.js">
</script>
<script language = "javascript" type="text/javascript" src="main.js">
</script>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("User Name");
var password =prompt("Password");
var loginWorked = false;
if (name!=null && name!="") loginWorked = init(name,password);
if(loginWorked == true){
window.location = "Toolbar.html"
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Login" />
</body>
</html>
And the code from my main file:
The init function:
function init(username,password){
//Initializes the toolbar.
init.user = username;
init.pass = password;
init.pass_hashed = sha256(init.pass);
var key = fetchKey(username);
init.pass_hashed += key;
init.pass_hashed = sha256(init.pass_hashed);
var loginParams = "login=1&pwd=" + init.pass_hashed + "&uname=" + init.user + "&LastKey=" + getKey();
loginReqReturn = send_request("http://data.nova-initia.com/login2.php","POST", loginParams);
if(loginReqReturn.responseText != "Error: Login Incorrect "){
return true;
}
else return false;
}
And the sendRequest method:
function send_request(theURL, theMethod, theParams)
{
var theReq = new XMLHttpRequest();
theReq.overrideMimeType("application/json");
theReq.open(theMethod,theURL,false);
if(typeof(theParams) === "string")
{
theReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
else
{
theReq.setRequestHeader("Content-type", "application/json");
theParams = JSON.stringify(theParams);
}
if(_key) theReq.setRequestHeader("X-NOVA-INITIA-LASTKEY", _key);
if(theParams)
{
theReq.send(theParams);
}
setKey(theReq);
return theReq;
}
Not the most efficient code, but it at least works when I execute it in a non-HTML context (I'm working on a toolbar for Google Chrome, but need the html overlay to work). Any help is much appreciated.
I'm not sure what your exact question is, but if you know that using JSONP is the solution that you can do that without using jQuery. Here's how it works: http://en.wikipedia.org/wiki/JSONP
If this is for a Google Chrome Extension, you can request permissions for cross-origin XMLHttpRequest requests within the extension's manifest:
{
...
"permissions": [
"http://data.nova-initia.com/"
],
...
}

Categories