I am trying to do this on client side using JavaScript.
Question: How to access JSON stored within https://www.instagram.com/xsolvesoftware/media/ with JavaScript and turn it into Object?
I tried xmlHttpRequest
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
var data = httpGet("https://www.instagram.com/xsolvesoftware/media/");
console.log(data);
I have tried loading it with src but it obviously doesn't work as it works only on content inside of tags:
var jsonData = JSON.parse(document.getElementById('data').textContent)
<script id="data" type="application/json" src="https://www.instagram.com/xsolvesoftware/media/">
</script>
I have tried editing this example but it uses JSONP not JSON as a reply and i think i would get JSONP only if i would use registered with access to users content:
var token = '1362124742.3ad74ca.6df307b8ac184c2d830f6bd7c2ac5644',
num_photos = 10,
container = document.getElementById( 'rudr_instafeed' ),
scrElement = document.createElement( 'script' );
window.mishaProcessResult = function( data ) {
for( x in data.data ){
container.innerHTML += '<li><img src="' + data.data[x].images.low_resolution.url + '"></li>';
}
}
scrElement.setAttribute( 'src', 'https://api.instagram.com/v1/users/self/media/recent?access_token=' + token + '&count=' + num_photos + '&callback=mishaProcessResult' );
document.body.appendChild( scrElement );
<ul id="rudr_instafeed"></ul>
have you already tried it?
What is you concrete problem?
If you have already tried, you could provide some code snippets and explain what you are struggeling with? (edit: you edited the question and added some code snippets, I'll have a look at them now)
From the distance it sounds like you are running into the CORS trap.
You need a backend service that fetches the json for you running on the same origin as you page is served from. This answer is a good starting point :)
Hope this helps.
edit: Had a look at your snippets and it is like I assumed: you have a problem with CORS. Your javascript is not allowed to load data from any arbitrary URL.
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>
Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.
I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)
I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.
Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.
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...