Can you catch a connection error? - javascript

I tried a lot of things to catch the error of this code but somehow I couldn't catch its error.
I have tried the try and catch(err) method but the error just pops up. Can't find an article on how to catch server connection errors either. They pop up in my console log but I can't seem to catch them. Here is what I've tried so far... well one of the ways I tried.
function timrec(){
try{
var time;
var inter1sec = setInterval(frame, 1000);
function frame() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
time = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = "Date is: "+time.d+"-"+time.m+"-"+time.y+" <br> Time is: " +time.h+":"+time.mi+":"+time.s+ " <br> day of the week is: "+ time.dow + "<br>";
}; }
xmlhttp.open("GET", "date.php",true);
xmlhttp.send();
}
}
catch(err){
alert("Warning! Connection error! Server might be down!");
}
}
I use the code to get the time of the server by intervals but can't seem to catch its error when I try and refresh my WAMP server to simulate a server connection failure.
Is it even possible to catch that?
If it's possible can ya share? And if it's not... thennnnn this'll be a fail. Either that, or my professor just threw me a trick question or something. Not gonna be the first time tho. :/

Use this code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://www.google.com", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) { // request completed. we have some results
if (xmlhttp.status === 200) {
console.log(xmlhttp.responseText)
} else {
console.log("Oops", xmlhttp.statusText);
}
}
};
xmlhttp.send(null);

Related

Track javascript runtime errors

Is there any way to capture all type of console errors?
Actually, I want to store all console errors to the database so I can fix serious issues of my PHP website.
Here is my current code to catch errors but this code is not capturing internal server errors and some other kind of errors like
www-widgetapi.js:99 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided ('https://www.youtube.com') does not match
the recipient window's origin
Current script that I have
function ErrorSetting(msg, file_loc, line_no) {
var e_msg=msg;
var e_file=file_loc;
var e_line=line_no;
var error_d = "Error in file: " + file_loc +
"\nline number:" + line_no +
"\nMessage:" + msg;
if(logJsErrors){
theData = "file="+file_loc+"&line="+line_no+"&err="+msg;
ajaxCtrl(
function(){
return true;
},Helpers.RootURL()+"/logs/index",theData
);
}
if(isDebugging){
console.error(error_d);
}
return true;
}
window.onerror = ErrorSetting;
I really appreciate your efforts.
Thank you :)
You could perform a kind of prototype of console.log, when you call console.log an ajax is fired, so you could do somethig like this:
(function () {
var postCons = console.log;
console.log = function (err) {
var xhttp = new XMLHttpRequest();
postCons.apply(this, arguments);
xhttp.open("POST", "log.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {//you could avoid this step
alert(this.responseText);//response from php
}
};
xhttp.send("data="+encodeURI(err));
}
})()
In log.php you could do whatever you want with $_POST['data'] , you could use something like urldecode($_POST['data']) .

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

How to wait for ajax request to complete in javascript when synchronous option is not available?

I'm trying to wait for the AJAX request to complete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ');
that.debug('-- ResponseText: "'+data+'"')
}
}
}
while (ajaxFinished == false) {
}
this.debug("-- open connection");
xmlhttp.open("GET", requestUrl, true); /* Ant Galio does not support synchronous */
this.debug("-- send");
xmlhttp.send();
I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.
Thanks!
yes, you can
function getFile(url) {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("GET", url, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var fileFromServer = getFile('http://somedomain.com/somefile.txt');
w3c definition http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
client . open(method, url [, async = true [, user = null [, password = null]]])
You can't. There is no "active waiting" in JavaScript, there can be only one active execution a time ("single-threaded").
There is a workaround.
Instead of using the the blocking while loop for poll use the nonblocking setInterval()..
so your code might look something like this.
var ajaxFinished = false;
var xmlhttp = new XMLHttpRequest();
this.debug("-- onreadystatechange is being defined");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
ajaxFinished = true;
var data = xmlhttp.responseText;
if (xmlhttp.status == 200) {
that.debug('downloadSettings: SUCCESS');
[...]
} else {
that.debug('downloadSettings:');
that.debug('-- Error: ");
that.debug('-- ResponseText: "'+data+'"')
}
}
}
//Polling function
function checkEvent(){
if(ajaxFinished == true){
//your code i.e xmlhttp.open("GET", requestUrl, true);
}
clearInterval(chkeventid);//Clear Interval via ID for single time execution
}
var chkeventid=self.setInterval("checkEvent()",100);//The poll call
The setInterval method is treated a bit differently in JS as you know so you may use it as against the while loop.

Parse Error Where Nothing Is Wrong

I'm making a mobile site using Dashcode to help me creating better UIs, but the problem is that I'm getting a strange Parse Error on my code, where nothing is wrong... This is the code:
function get_currency(from, to) {
var XMLHttp; // Create the Ajax handler
XMLHttp = new XMLHttpRequest();
var url = "http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to + "=X";
XMLHttp.open("GET", url, true);
XMLHttp.onreadystatechange = function() {
if(XMLHttp.readyState == 4) {
/* Once the server has completed its tasks display the result */
var response = XMLHttp.responseText;
var parsed_reply = response.split(',');
document.getElementById('txtAmount').value = parsed_reply[1];
}
XMLHttp.send(null);
}
function btConvert_Click(event)
{
get_currency("BRL", "USD");
}
The error is occurring(According to the debugger) at the line 209(the last line of the code), which is the } a the end of this code that I gave. What's wrong?
You're missing a closing } for your onreadstatechange handler, causing the parser to puke at the end of the script. Given the indentation, it's the closing } for the if(XMLHttp.readyState...) check
You're missing a }
Based on your spacing, you haven't closed the { from
if(XMLHttp.readyState == 4) {

basic xmlHttp question

I 'm having some trouble with my javascript code calling my php. Does anyone see an error in the following code? I swear I'm using code just like this on another part of the site...
var xmlHttp = createXmlHttpRequestObject();
var favSongArray = [];
function createXmlHttpRequestObject(){
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch(e){}
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp){
alert("sever is available");
//if yes try
try{
xmlHttp.open("GET", "php/getUntimed.php", true);
xmlHttp.onreadystatechange = function(){handleRequestStateChange();};
alert("attempted to call p_handleRequestStateChange_test");
xmlHttp.send(null);
}//end try
catch(e){
alert("Can't connect to server: \n" + e.toString());
}//end catch
}//end if xmlHHttp
}//end function
function handleRequestStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
u_handleServerResponse();
}//end try
catch(e){
alert("Error reading the response: " +e.toString());
}//end catch
}//end if
else{
alert("There was a problem retriving the data:\n" + xmlHttp.statusText);
}//end else
}//end if
}//end function
function u_handleServerResponse(){
//need to clear array each time
var response = xmlHttp.responseText;
favSongArray = response.split("+");
alert("made it here");
//getFlashMovie("trackTimer").trackTimer(favSongArray[0]);
}
process() is called from an onSubmit trigger. I keep getting a xmlHttp.status of zero. Does that make sense to anyone? Thanks
status == 0 usually means it was aborted -- either by pressing ESC or by changing the current address.
Or, since you're using a global xmlHttp, you may be calling open and/or send before the last request has had time to finish. Not entirely sure which, but one of them starts by calling abort.
Just navigate here.
http://docs.jquery.com/Ajax
Simple Example:
$.get('MyUrl.aspx', 'MyId=' + id, function(data){
$(data).appendTo($('#MyDiv'));
});
As Jonathan Lonowski says, status == 0 means aborted, and you said you execute that script onsubmit which would trigger the form to submit, thus reload the page and aborting the Ajax request. Take a look here too.
Why don't you try using ajax frameworks? Like jQuery for example.

Categories