Jump to content

xml http request


Destramic
Go to solution Solved by requinix,

Recommended Posts

i'm wanting to check if the web-socket is open...i'm using a xml http request...unless there's is a better way you can suggest

 

using the code below returns undefined

function web_socket_open(href){
	    var request = new XMLHttpRequest(href);
	    
	    request.onreadystatechange = function() { 
	        if (request.readyState === 4 && request.status === 200) {
	        	   return true;
	        }

	        return false;
	    }  
	}

	console.log(web_socket_open('http://127.0.0.1:8080'));

what am i doing wrong here please?

 

thank you

Link to comment
Share on other sites

  • Solution

AJAX is asynchronous - it does not happen linearly with the rest of your code. web_socket_open() will finish executing immediately and then eventually sometime later the onreadystatechange function will fire. Nevermind that the return will only return from that anonymous function and not web_socket_open().

function web_socket_open(href){
	var request = new XMLHttpRequest(href);
	    
	request.onreadystatechange = function() { 
		if (request.readyState === 4 && request.status === 200) {
			console.log(true);
		}

		console.log(false);
	}  
}

web_socket_open('http://127.0.0.1:8080');
And notice that if everything is good you'll see a true and false output.
Link to comment
Share on other sites

never heard of websocket class looked at it...but not sure what to do to be honest.

 

 

AJAX is asynchronous - it does not happen linearly with the rest of your code. web_socket_open() will finish executing immediately and then eventually sometime later the onreadystatechange function will fire. Nevermind that the return will only return from that anonymous function and not web_socket_open().

function web_socket_open(href){
	var request = new XMLHttpRequest(href);
	    
	request.onreadystatechange = function() { 
		if (request.readyState === 4 && request.status === 200) {
			console.log(true);
		}

		console.log(false);
	}  
}

web_socket_open('http://127.0.0.1:8080');
And notice that if everything is good you'll see a true and false output.

 

 

ideally i would like to know if the socket was down...that way i can display page not available or something (fingers crossed that doesn't happen)...but just a precaution.

 

is there a better way to do this please?...i ran script and waited ages with no console log

 

thank you

Link to comment
Share on other sites

is there a better way to do this please?...i ran script and waited ages with no console log

Is what you posted your real code? Because it's incomplete. Like, you need a call to .send() in there.

 

You said you wanted to connect to a websocket, and the WebSocket object is how you do that.

I'm not sure he meant "websockets" as in the tech - more like "open a socket to a website" in the general networking terms.
Link to comment
Share on other sites

sorry i haven't been around to test and get back to you

 

i've tried running this code...which returns not connected twice before returning connected...how can i get it just to return one or the other please?

	var xhr = new XMLHttpRequest();

	
	xhr.open('GET', 'http://127.0.0.1:8080', true);
	xhr.send(null);
	
	xhr.onreadystatechange = function() {
	    if (xhr.readyState === 4  && xhr.status === 200) {
		        console.log('connected')
	    }
	    else
	    {
	    	 console.log('not connected')
	    }
	}

thank you

Link to comment
Share on other sites

The ready state changes more than once during the lifetime of the connection. That's why there is a .readyState value you can look at.

 

Only make a decision regarding connected/not connected when readyState is 4, which corresponds to the request having completed.

Link to comment
Share on other sites

The ready state changes more than once during the lifetime of the connection. That's why there is a .readyState value you can look at.

 

Only make a decision regarding connected/not connected when readyState is 4, which corresponds to the request having completed.

 

 

sorry requinix im not sure if what i'm trying to do is not possible of i'm doing something wrong here:

$(document).ready(function(){
	function web_socket_open(){
		var xhr = new XMLHttpRequest();

		xhr.onreadystatechange = function() {
		    if (xhr.readyState === 4) {
		        if (xhr.status === 200){
		            console.log('yes'); // returns 
			    	  return true;
		        }

		        return false;
		    }
		}

		xhr.open('GET', 'http://127.0.0.1:8080', true);
		xhr.send(null);
	}

	if (web_socket_open()){
		   console.log('yes');
		}
	else
	{
		console.log('no');
	}
});

when executing the web_socket_open function it returns no (returning false in if statement)...then in console log it shows yes during the http request, which comes from the function itself..

 

ideally i would like it just to return true as it should do? as url is correct

 

thanks for your help.

Link to comment
Share on other sites

As requinix already told you in the beginning of the thread (see reply #2), JavaScript doesn't work like this. The web_socket_open() function doesn't wait for the inner function. It registers the inner function as a handler for the readystatechange event and then returns immediately, long before your return statements take effect. Your statements also refer to the inner function, not web_socket_open().

 

This actually works like with any other event handler. In your main JavaScript code, you probably assign a lot of functions to click events, mouseover events etc. Does your entire code pause until the user has finally clicked on some button and made the event handler return? No, the code just registers the event handler, and then later the handlers are called.

 

It's really important that you understand the asynchronic nature of JavaScript. If you want to do something based on whether or not the web socket was opened successfully, you need a callback function which you pass to web_socket_open(). As soon as the socket was opened, you call that function.

Link to comment
Share on other sites

yeah sorry...

 

ok well i think something like this would work a lot better

$(document).ready(function(){
    function socket_open(port, https){    
        var location = window.location,
            host     = location.hostname,
            protocol = "http";
            
        if (https){
            protocol = "https";
        }
        
        var url = protocol + '://' + host + ':' + port;
        console.log(url);

        $.ajax({
            'url' : url,
            'success' : function() {
                  return true;
            },
            'error' : function() {
                return false;
                }
          });
    }
    
    if (socket_open(8080)){
        console.log("successful");
    }
    else{
        console.log('error');
    }
});

just one problem with this though the url has apostrophes around it causing the function to always return false.

 

i tied to replace apostrophes in var url but still didnt work

 

like i said i just want a script like this just in case the socket goes down, that way i can show something like page temporary down / redirect

 

thanks guys

Link to comment
Share on other sites

You. Cannot. Return. From. The. Success. Or. Failure. Handlers.

 

It will NOT make the socket_open() function return a value.

 

If you want to log to the console (or do something else) on success or on failure then put that code inside the handlers themselves.

Link to comment
Share on other sites

You could do this, if you think it's cleaner. I believe this is what Jacques1 is suggesting.

$(document).ready(function(){
function socket_open(port, https, success, failure){
var location = window.location,
host = location.hostname,
protocol = "http";

if (https){
protocol = "https";
}

var url = protocol + '://' + host + ':' + port;
console.log(url);

$.ajax({
'url' : url,
'success' : success,
'error' : failure
});
}

socket_open(8080, null, function(){
console.log('successful');
}, function(){
console.log('error')
});
});
Otherwise, you could use a Promise. Then you could do this:
socket_open(8080).then(function(){
console.log('successful');
});
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.