I'm writing a simple AJAX call that returns a full HTML page and then I attempt to get some values I need from this response. I dont know why its not working and I've done everything I could possibly think of. It works when I have my code as part of another HTML page but not as part of a Firefox extension and thats the problem: I'm writing a Firefox extension!
In the Firefox extension I get a response and I can alert, and its there (i.e. I see the response text)! but I cant call .find, .filter or anything else really. The code breaks silently at some point in the success function and nothing happens.
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').click(function(){
var makeTransferURL = "empty";
var pc = "empty";
$.ajax({//Transfer
type: "POST",
url: "http://localhost/transfer2.html",
data: "",
dataType: "html",
context: document.body,
success: function(response){
var table = $(response).find('table.123RowSeparator');
var a = table.find('a[href*="123"]');
var href = a.attr("href");
makeTransferURL = href;
var link = makeTransferURL.indexOf('PC_');
pc = makeTransferURL.substring(link, (link + 11));
alert(pc);
},
error: function() {
alert("Sorry, The requested property could not be found.");
}
});
});
});
</script>
</head>
<body>
<input type="button" value="load" />
</body>
</html>
The exact same code as a firefox extension doesnt work:
window.addEventListener("load", function() { myExtension.init(); }, false);
var myExtension = {
init: function() {
gBrowser.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
if(doc.location.href=="http://localhost/index2.html") {
var makeTransferURL = "empty";
var verifyTransferURL = "empty";
var confirmTransferURL = "empty";
var token1 = "empty";
var token2 = "empty";
var pc = "empty";
$.ajax({//Transfer
type: "POST",
url: "http://localhost/transfer2.html",
data: "",
cache: false,
async: false,
dataType: "html",
context: document.body,
success: function(response){
var table = $(response).find('table.123RowSeparator');
var a = table.find('a[href*="123"]');
var href = a.attr("href");
makeTransferURL = href;
var link = makeTransferURL.indexOf('PC_');
pc = makeTransferURL.substring(link, (link + 11));
alert(pc);
},
error: function() {
alert("Sorry, The requested property could not be found.");
}
});
}
aEvent.originalTarget.defaultView.addEventListener("unload", function(){ myExtension.onPageUnload(); }, true);
},
onPageUnload: function(aEvent) {}
}
I need to know why!
Here is the HTTP header of the response:
HTTP/1.1 200 OK
Date: Mon, 11 Jul 2011 10:43:32 GMT
Server: Apache/2.2.19 (Win32)
Last-Modified: Wed, 06 Jul 2011 12:41:47 GMT
ETag: "9000000015529-f7b9-4a765ec7780ff"
Accept-Ranges: bytes
Content-Length: 63417
Keep-Alive: timeout=5, max=97
Connection: Keep-Alive
Content-Type: text/html
Found the solution, its not elegant(or correct practice) but give me a break! No one answered :)
Here is what I did to get this to work:
$('#divid').css('display', 'none');
response = response.replace(/<head>(?:.|\n|\r)+?<\/head>/ig, "");
doc.getElementById('divid').innerHTML = response.replace(/<script[^>]*>[\S\s]*?<\/script[^>]*>/ig, "");
var table = $('#divid').find('whateveryoufeellike');
So I think the problem was that I was getting a plain HTML formatted string and I couldn't use jQuery functions like .find and .filter on a string like that. Took the string and using regex, striped it off of its head and script tags and (probably do images too soon) dumped what was left in a Div I created. But not before setting the div to be hidden so that the code doesn't show. The user feels no difference really and I can now use the DOM for the mother page and take run all the .finds and .filters my heart desires!
There beauty of it is that there wont be any collision issue between tags with same id/class on the same page as long as the name of the Div you make in your page is unique to that page. So something really random would be a good choice :D suggestions... !HWSyujtewq$y$y$w£t!"£%^(&)%$dsfdgjnbfdvsc
Related
i've put together this code that in my (null) experience should be close to do what i need ( add utm to current link, convert it to bitly and then copy to clipboard)
ive tried to debug as much as i can, but as i say im not an expert on Javascript and cuold not get very far, also havent been able to troubleshoot from Devtools on chrome since it is an extension, but basically im getting the correct address but (html has a popup with the correct address) its not copying anything to the clipboard. what did i do wrong? (this code is a mix of other sources, as i said i dont know javascript, i mostly use python and im no expert there either.
Script.js:
window.onload = function() {
function ShortLinkBitly( pLongUrl ) { /*pLongUrl is the long URL*/
if ( !pLongUrl.match(/(ftp|http|https):\/\//i) ) {
return "Error: Link must start with a protocol (e.g.: http or https).";
}
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXX';
var username = 'XXXXXXX';
/*Ajax call*/
$.ajax(
{
url: 'https://api-ssl.bitly.com/v3/shorten?login=' + username + '&apiKey=' + apiKey + '&format=json&longUrl=' + encodeURIComponent(pLongUrl),
dataType: 'jsonp',
success: function( response ) {
if ( response.status_code == 500) {
/*500 status code means the link is malformed.*/
return "Error: Invalid link.";
} else if ( response.status_code != 200) {
/*If response is not 200 then an error ocurred. It can be a network issue or bitly is down.*/
return "Error: Service unavailable.";
/*Uncomment the following line only for debugging purposes*/
/*console.log('Response: ' + response.status_code + '-' + response.status_txt);*/
}
else
return response.data.url; /* OK, return the short link */
},
contentType: 'application/json'
});
}
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var urlArea = document.getElementById("urlArea");
urlArea.innerHTML = tabs[0].url.concat("?utm_medium=callcenter&utm_source=callcenter&utm_campaign=TestMauro");
var URL = urlArea.innerHTML
URL = ShortLinkBitly(URL)
var dummy = document.createElement("input");
document.body.appendChild(dummy);
dummy.setAttribute('value', URL);
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
document.getElementById("title").innerHTML = "Link copied successfully";
});
}
index.html:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="scripts.js"></script>
</head>
<body>
<h3 id="title">Copylink</h3>
<textarea id="urlArea"></textarea>
</body>
</html>
I also checked my bitly account and no address has been created so clearly something is not working there?
Thanks all!
I'm using Ajax/jQuery to pull in some content from an RSS feed, but it seems to be failing to read the content of an XML node with the name 'link'.
Here's a simplified version of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<channel>
<item>
<title>Title one</title>
<link>https://example.com/</link>
<pubDate>Mon, 12 Feb 2019</pubDate>
</item>
<item>...</item>
<item>...</item>
</channel>
</xml>
And the code I'm using:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('item', this.responseText).each(function(){
var thisPostData = {};
thisPostData.title = $(this).find('title').text();
thisPostData.link = $(this).find('link').text();
thisPostData.date = $(this).find('pubDate').text();
posts.push(thisPostData);
});
console.log(posts);
}
};
var posts = [];
xhttp.open('GET', 'https://example.com/rssfeed/', true);
xhttp.send();
You'll see I'm trying to add each 'item' to an object, and storing them inside the 'posts' array. 'Title' and 'pubDate' are stored fine but 'link' isn't.
The actual RSS feed in question contains a huge amount of extra data, all of which I can read except the 'link' nodes. Any suggestions why nodes called 'link' would act differently from all the others?
The problem is because you're attempting to parse XML as HTML. The <link> object in HTML is an inline element, not a block level one, so it has no textContent property for jQuery to read, hence the output is empty.
To fix this first read the XML using $.parseXML(), then put it in a jQuery object which you can traverse.
There's also a couple of things to note. Firstly you will need to remove the </xml> node at the end of the XML output as it's invalid and will cause an error when run through $.parseXML. Secondly you can use map() to build an array instead of manually calling push() on an array, and you can just return the object definition directly from that. Try this:
var responseText = '<?xml version="1.0" encoding="UTF-8"?><channel><item><title>Title one</title><link>https://example.com/</link><pubDate>Mon, 12 Feb 2019</pubDate></item><item><title>Title two</title><link>https://foo.com/</link><pubDate>Tue, 13 Feb 2019</pubDate></item></channel>';
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
console.log(posts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Lastly, you're using a rather odd mix of JS and jQuery. I'd suggest going with one or the other. As such, here's a full jQuery implementation with the AJAX request included too:
$.ajax({
url: 'https://example.com/rssfeed/',
success: function(responseText) {
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
// work with posts here...
}
});
This is a question in relation to this one.
In UPDATE II, I added a script based on Jamie's feedback.
UPDATE - tl;dr:
I created a fiddle with a temporary key so you guys can see the problem more easily: http://jsfiddle.net/S6wEN/.
As this question was getting too long, this is a summary.
I tried to use imgur API to update an image via cross domain XHR.
In order to abstract details in the implementation, I'm using Jquery Form Plugin (obviously, it's contained in the fiddle).
Works great in Chrome, Firefox, etc but it doesn't work in IE9.
The expected result is to update the image and retrieve image type.
You can still find the details below.
Thanks
I have this HTML:
<body>
<form id="uploadForm" action="http://api.imgur.com/2/upload.xml" method="POST" enctype="multipart/form-data">
<input type="hidden" name="key" value="MYKEY">
File: <input type="file" name="image">
Return Type: <select id="uploadResponseType" name="mimetype">
<option value="xml">xml</option>
</select>
<input type="submit" value="Submit 1" name="uploadSubmitter1">
</form>
<div id="uploadOutput"></div>
</body>
So basically, I have a form to upload an image to imgur via cross domain XHR. In order to manage the nasty details, I'm using Jquery Form Plugin, which works well. However, when I try to send an image to imgur and receive an xml response, it doesn't work as expected in IE9 (I haven't tested in IE8 but I don't expect great news). It works great in Chrome and Firefox. This is the javascript part:
(function() {
$('#uploadForm').ajaxForm({
beforeSubmit: function(a,f,o) {
o.dataType = $('#uploadResponseType')[0].value;
$('#uploadOutput').html('Submitting...');
},
complete: function(data) {
var xmlDoc = $.parseXML( data.responseText ),
$xml = $( xmlDoc );
$('#uploadOutput').html($xml.find('type'));
}
});
})();
In IE9 I receive the following errors:
SCRIPT5022: Invalid XML: null
jquery.min.js, line 2 character 10890
XML5619: Incorrect document syntax.
, line 1 character 1
I also used the example given in Jquery Form Plugin's page, which uses only Javascript but it doesn't help. Obviously, the first error referring to Jquery disappears but I can't obtain the expected results (in this case, image/jpeg in the div with id="uploadOutput" ).
When I look at the console in IE9, I get this:
URL Method Result Type Received Taken Initiator Wait Start Request Response Cache read Gap
http://api.imgur.com/2/upload.xml POST 200 application/xml 1.07 KB 7.89 s click 2808 93 5351 0 0 0
and as body response:
<?xml version="1.0" encoding="utf-8"?>
<upload><image><name/><title/><caption/><hash>xMCdD</hash>
<deletehash>Nb7Pvf3zPNohmkQ</deletehash><datetime>2012-03-17 01:15:22</datetime>
<type>image/jpeg</type><animated>false</animated><width>1024</width
<height>768</height><size>208053</size><views>0</views><bandwidth>0</bandwidth></image
<links><original>http://i.imgur.com/xMCdD.jpg</original
<imgur_page>http://imgur.com/xMCdD</imgur_page>
<delete_page>http://imgur.com/delete/Nb7Pvf3zPNohmkQ</delete_page>
<small_square>http://i.imgur.com/xMCdDs.jpg</small_square>
<large_thumbnail>http://i.imgur.com/xMCdDl.jpg</large_thumbnail></links></upload>
which is all fine, but for some reason, I can't process that information into the HTML page. I validated the XML, just to be sure that wasn't the problem. It is valid, of course.
So, what's the problem with IE9?.
UPDATE:
Another way to fetch XML which works in Chrome and Firefox but not in IE9:
(function() {
$('#uploadForm').ajaxForm({
dataType: "xml",
beforeSubmit: function(a,f,o) {
o.dataType = $('#uploadResponseType')[0].value;
$('#uploadOutput').html('Submitting...');
},
success: function(data) {
var $xml = $( data ),
element = $($xml).find('type').text();
alert(element);
}
});
})();
UPDATE 2:
<!DOCTYPE html>
<html>
<body>
<form id="uploadForm" action="http://api.imgur.com/2/upload.xml" method="POST" enctype="multipart/form-data">
<input type="hidden" name="key" value="00ced2f13cf6435ae8faec5d498cbbfe">
File: <input type="file" name="image">
Return Type: <select id="uploadResponseType" name="mimetype">
<option value="xml">xml</option>
</select>
<input type="submit" value="Submit 1" name="uploadSubmitter1">
</form>
<div id="uploadOutput"></div>
</body>
</html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
(function() {
var options = {
// target: '#output1', // target element(s) to be updated with server response
//beforeSubmit: showRequest, // pre-submit callback
success: afterSuccess, // post-submit callback
complete: afterCompletion,
// other available options:
//url: url // override for form's 'action' attribute
type: 'POST', // 'get' or 'post', override for form's 'method' attribute
dataType: 'xml' // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
function process_xml(xml) {
var type = $(xml).find('type').text() ;
return type;
// Find other elements and add them to your document
}
function afterSuccess(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property
// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server
var $xml = process_xml(responseText);
console.log('success: ' + $xml);
}
function afterCompletion(xhr,status){
if(status == 'parsererror'){
xmlDoc = null;
// Create the XML document from the responseText string
if(window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(xhr.responseText,"text/xml");
} else {
// Internet Explorer
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(xhr.responseText);
}
}
console.log('complete: ' + process_xml(xhr.responseText));
}
$('#uploadForm').ajaxForm(options);
})();
</script>
Thanks in advance.
IE is notoriously fussy when it comes to accepting XML and parsing it. Try something like this:
function process_xml(xml) {
var type = $(xml).find('type').text() ;
$('#type').html(type) ;
// Find other elements and add them to your document
}
$(function() {
$('#uploadForm').ajaxForm({
dataType: "xml", // 'xml' passes it through the browser's xml parser
success: function(xml,status) {
// The SUCCESS EVENT means that the xml document
// came down from the server AND got parsed successfully
// using the browser's own xml parsing caps.
process_xml(xml);
// Everything goes wrong for Internet Explorer
// when the mime-type isn't explicitly text/xml.
// If you are missing the text/xml header
// apparently the xml parse fails,
// and in IE you don't get to execute this function AT ALL.
},
complete: function(xhr,status){
if(status == 'parsererror'){
xmlDoc = null;
// Create the XML document from the responseText string
if(window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(xhr.responseText,"text/xml");
} else {
// Internet Explorer
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(xhr.responseText);
}
process_xml(xml);
}
},
error: function(xhr,status,error)
{
alert('ERROR: ' + status) ;
alert(xhr.responseText) ;
}
});
});
Also,use alert() throughout debugging to provide feedback on what information is being passed through at all times.
EDIT
The crucial thing is ensure your XML file is 'well-formed', i.e. it must not contain any syntax errors. You need to begin the XML file with:
<?xml version="1.0"?>
It's not so much a server issue because, the errors come from your browser (i.e. Internet Explorer) because it thinks the XML is malformed. The error comes from your browser and indicates that your XML is malformed. You can manually set what headers you want returned with these $.ajax() settings:
dataType: ($.browser.msie) ? "text" : "xml",
accepts: {
xml: "text/xml",
text: "text/xml"
}
Or another way to do the same thing is to ask for a particular header:
headers: {Accept: "text/xml"},
The difference between the content-types application/xml and text/xml are minor (it's based on each XML's charset), but if you want to know you can read this post.
Perhaps give this a try? I use this with a google maps store locator. I notice $.parseXML actually does this internally, but its within a try/catch, and its saying your data is null (which is weird?)
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
From jQuery:
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
I have used that plugin before. If I recall this right it is using an iframe to fetch the information and then it is reading the content in the iframe. The content is stored in the property responseText. But IE may have stricter rules than other browsers. Have you tried printing out the value of data.responseText?
If the value is not a XML string. I hate to say it but the API isn't made for Javascript. What I've learned is that JSONP with manipulating the script tags is the best way to do cross domain XHR. Which I don't think this plugin does.
demo: http://bit.ly/HondPC
js code:
$(function() {
$('#uploadForm').ajaxForm({
dataType : 'xml', // OR $('#uploadResponseType option:selected').val()
beforeSubmit : function(a, f, o) {
$('#uploadOutput').html('Submitting...');
},
success : function(data) {
var original = $(data).find('links').find('original').text();
$('#uploadOutput').html('<img src="' + original + '" alt="" />');
}
});
});
php code:
<?
$api_key = "****************************";
$file = getcwd() . '/' . basename( $_FILES['image']['name'] );
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$handle = fopen($file, "r");
$data = fread($handle, filesize($file));
$pvars = array('image' => base64_encode($data), 'key' => $api_key);
$post = http_build_query($pvars);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec($curl);
curl_close ($curl);
unlink($file);
header('Content-type: text/xml');
echo $xml;
?>
I have some code that performs an AJAX call to the google currency calculator. Which in theory should return a JSON array that i can ten use to get some exchange rate related data.
The Link is:
http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY
Going to the link shows
{lhs: "1 U.S. dollar",rhs: "6.49148317 Chinese yuan",error: "",icc: true}
My javascript code (I tired this with both POST and GET):
jQuery.ajax({
type: "GET",
url: "http://www.google.com/ig/calculator",
data: "hl=en&q=1USD=?CNY",
success: function(msg) {
var currency = $.parseJSON(msg);
alert (currency ['rhs'];);
}
});
Examining fire bug shows in red with an empty response
GET http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY 200 OK 255ms
What am I doing wrong?
You can't perform cross domain requests with jQuery. You need to use JSONP to perform this request. These links might help:
http://api.jquery.com/jQuery.getJSON/#jsonp
jsonp with jquery
JSONP requests are not subject to same-origin policy restrictions.
heard google has stopped services from iGoogle from Nov 1st..
the link no longer works.
As we know google has stopped services from iGoogle from Nov 1st/2013..
But we can use https://www.google.com/finance/converter to get the real time data.
Following example of jquery will work for you.
function CurrencyConvetor(amount, from, to) {
var result = '';
var url = "https://www.google.com/finance/converter?a=" + amount + "&from=" + from + "&to=" + to;
$.ajaxSetup({async: false});
$.get(url,
function (data) {
var startPos = data.search('<div id=currency_converter_result>');
var endPos = data.search('<input type=submit value="Convert">');
if (startPos > 0) {
result = data.substring(startPos, endPos);
result = result.replace('<div id=currency_converter_result>', '');
result = result.replace('<span class=bld>', '');
result = result.replace('</span>', '');
}
})
return result;
}
I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...