I'm trying to make an AJAX-Request within a Wordpress Plugin in frontend, after clicking a button. -> Actually it is a Widget. So I implemented the frontend via extending de WP_Widget Class. I don't know if this is worth knowing.
I always get a 400 bad Request and '0'.
I dont wanted to use JQuery, but i also tried and there I get a 500 Internal Server Error.
Now im really confused.
I really searched up and down the internet and every question in this forum (I know there are many similar questions - but nothing worked to me)
I'm so thankful if anyone can help me.
Main Plugin File:
function scriptloader(){
$scripturl = plugin_dir_url(__FILE__) . 'includes/public/script.js';
wp_enqueue_script('script-js', $scripturl, array( 'jquery' ));
$styleurl = plugin_dir_url(__FILE__) . 'includes/public/css/main.css';
wp_enqueue_style('script-js', $styleurl, [], null, false);
$js_variable = [
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce( 'ajax_public' ),
'mystring' => "LOL!"
];
wp_localize_script('script-js', 'phpwindowobject', $js_variable);
};
add_action( 'wp_enqueue_scripts', 'scriptloader');
function k_ajax_requester(){
$mystring = "SERVER ALIVE";
echo $mystring;
wp_die();
};
add_action('wp_ajax_k_ajax', 'k_ajax_requester');
add_action('wp_ajax_nopriv_k_ajax', 'k_ajax_requester');
There is a button in frontend.php which executes ajaxrequest() by clicking in
my script.js :
function ajaxrequest(){
var url = phpwindowobject.ajax_url;
var data = {action: "k_ajax",mystring: "K_AJAX"}
console.log("Data to send:")
console.log(data)
var xhrobj = new XMLHttpRequest;
xhrobj.open('POST', url, true);
xhrobj.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
xhrobj.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + xhrobj.statusText );
}
};
xhrobj.onload = function(){
var answer = (xhrobj.response);
console.log(answer);
}
xhrobj.send(data);
};
What do you think?
Thank you.
Related
I 'm trying to execute commands (wp cli) with xhr.
My problem is when i call my file deploy.php with the javascript.
Without JS call the script works, the flush is immediate.
When i call deploy.php in a XmlHttpRequest, the response wait until the end of the php execution.
I try different commands (grep / wp cli / find) but the result is the same.
I work on WSL Debian + Chrome.
// PHP
public function liveExecuteCommand($cmd, $ajax = false)
{
ob_start();
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error-output.txt", "a")
);
$output = '';
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
while ($s = fread($pipes[1], 8192)) {
$output .= $s;
print $s;
$this->doFlush();
}
fclose($pipes[1]);
$return_value = proc_close($process);
//echo "La commande a retourné $return_value\n";
}
if ($ajax == false) {
return $output;
}
}
$obj->liveExecuteCommand($cmd, true);
die();
// JS
function getLiveStream() {
var ajax = new XMLHttpRequest();
var url = 'https://www.monsite.local/deploy.php';
ajax.open('GET', url, true);
ajax.onprogress = function() {
document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
console.log('onprogress');
}
ajax.onload = function() {
console.log('onload');
}
ajax.onreadystatechange = function() {
document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
console.log('statechange');
}
ajax.send();
}
window.addEventListener('DOMContentLoaded', (event_loaded) => {
document.getElementById("xhr_cmd").onclick = getLiveStream;
});
In the Google chrome console, the result display all status directly (after 1 min), like the php result.
statechange
onprogress
statechange
onprogress
statechange
onprogress
statechange
onload
I would like have a console.log every time that the flush is called.
No problem when i execute the php file in the browser, the problem is certainly in the javascript.
How do I solve the problem?
Let me explain you in simple words.
Javascript's XMLHttpRequest(AJAX) call will request to server. It will only waits for response from server(final output from your php page), irrespective to internal process of server.
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.
i working on a simple script that load users last posts in there blog and website !
the page is works well without any problem !
this is an example : http://parsclub.net/tools/widget/load-rss.php?u=reza-shady&l=5&w=200&c=4DC7FF
i want to load that link blow in external page !
for that i used this script and put it on a file
<?php
$user = trim($_GET["u"]);
$limit = trim($_GET["l"]);
$width = trim($_GET["w"]);
$color = trim($_GET["c"]);
header("Content-Type: text/javascript; charset=utf-8");
?>
document.write('<div id="parsclub_widget"><img src="http://parsclub.net/themes/parsclub/imgs/loading_posts.gif" style="margin:20px;display:inline-block;"/></div>');
function ajaxRequest() {
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject) {
for (var i = 0; i < activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
} catch (e) {
}
}
} else if (window.XMLHttpRequest) return new XMLHttpRequest()
else return false;
}
function load_widget() {
var mygetrequest = new ajaxRequest()
if (mygetrequest.overrideMimeType) mygetrequest.overrideMimeType('text/html')
mygetrequest.onreadystatechange = function () {
if (mygetrequest.readyState == 4) {
if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1) {
var data = mygetrequest.responseText;
document.getElementById("parsclub_widget").innerHTML = data;
} else {
alert("خطایی در هنگام دریافت اطلاعات رخ داده است");
}
}
}
mygetrequest.open("GET", "http://parsclub.net/tools/widget/load-rss.php?u=<?= $user ?>&l=<?= $limit ?>&w=<?= $width ?>&c=<?= $color ?>", true);
mygetrequest.send(null);
return false;
}
load_widget();
but it don't work when i put it on a external page
you can see the result here !
http://up.pc-t.ir/New%20Text%20Document.html
i know i cant simply load it with jquery load() function but i want it pure JavaScript
can anyone help me with this ?
so sorry for my bad English
EDIT
#merlin-denker 10x for your help i found solution for my problem by adding this headers to the load-rss.php file
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
As Barmar already stated in a comment, the AJAX Request is failing because of the same origin policy.
The solution to this is to add a PHP-Script to your Website that simply reads the content of the other URL and echoes it.
<?php echo file_get_contents(YOUR_URL_HERE); ?>
Then let your Javascript call the script that is located on the same webserver and it will work.
Read more here: http://www.php.net/manual/function.file-get-contents.php
I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have poured through the docs and this and think it is 99% there.
Is what this app does is there is a list of items. Each one with a + button. Clicking the button pops up a confirm box, and if confirmed grabs the needed data to pass to the php. The php adds the item into mysql with wpdb->insert. It also does some changes if you buy.
The js works all the way up to the call, grabbing the right values etc. Testing the php separately works as well if I hard code the values it is supposed to grab from POST. So I KNOW both pieces run, I just can't get the js to call the ajax api right. Can someone please take a look at this and let me know how to hook these together so the ajax call actually runs the php?
Here is the code.
<?php
add_action( 'admin_footer', 'addItemAJAX_javascript' );
function addItemAJAX_javascript() {
$adminAJAX = admin_url('admin-ajax.php');
?>
<script type="text/javascript" language="JavaScript">
$(function() {
$( "input[name=btnAddItem]" )
.button()
.click(function( event ) {
event.preventDefault();
var confirmAction = confirm('Are you sure you want to add this item to your character?');
if (confirmAction==true) {
// build data for AJAX call
var cID = $('#hdnCharID').val();
cID = cID*1;
var charMoney = $('#hdnCharMoney').val();
var thisValue = $(this).val();
var iID = $(this).prev('input[id="hdnItemID"]').val()
iID = iID*1;
//Add or Buy Item
if (thisValue != "+") {
var buy = 1;
}
else {
var buy = 0;
}
var ajaxurl = <?php echo json_encode($adminAJAX); ?>;
console.log('cID = ' + cID);
console.log('charMoney = ' + charMoney);
console.log('thisValue = ' + thisValue);
console.log('iID = ' + iID);
console.log('buy = ' + buy);
console.log('ajaxurl = ' + ajaxurl);
var data = {
action: 'addItemAJAX',
charID: cID,
itemID: iID,
buyItem: buy
};
console.log('data = ' + data);
console.log(data);
//WP ajax call
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
else {
console.log('add item aborted');
}
});
});
</script>
<?php
};
addItemAJAX_javascript();
// PHP SIDE OF AJAX - Handeling Request //// AJAX PROCESSING /////////////////////////////////
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
function addItemAJAX_callback() {
global $wpdb;
$charID = intval($_POST['charID']);
$itemID = intval($_POST['itemID']);
$buyItem = intval($_POST['buyItem']);
// //get item details
$getItemDetailsSQL = "
Select
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_name,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_description,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_cost,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_weight
From
fyxt_wp_db_fatcow.fyxt_items
Where
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items = $itemID";
$getItemDetailsResults = $wpdb->get_row($getItemDetailsSQL);
$iID = $getItemDetailsResults->idfyxt_items;
$iName = $getItemDetailsResults->fyxt_item_name;
$iDesc = $getItemDetailsResults->fyxt_item_description;
$iCost = $getItemDetailsResults->fyxt_item_cost;
$iWeight = $getItemDetailsResults->fyxt_item_weight;
$charItemTable = fyxt_char_items;
$wpdb->insert(
$charItemTable,
array (
idfyxt_item => $iID,
idfyxt_character => $charID,
item_name => $iName,
item_desc => $iDesc,
item_cost => $iCost,
item_weight => $iWeight,
item_quant => 1,
equip => 0,
carried => 1
)
);
$wpdb->print_error();
$newItemAdded = $wpdb->insert_id;
//remove cash if item is bought
if ($buyItem == 1 ) {
$curCharMoneySQL =
"Select
fyxt_wp_db_fatcow.fyxt_characters.char_money
From
fyxt_wp_db_fatcow.fyxt_characters
Where
fyxt_wp_db_fatcow.fyxt_characters.idfyxt_character = $charID";
$curCharCash = $wpdb->get_var($curCharMoneySQL);
$wpdb->print_error();
$newCash = $curCharCash - $iCost;
$changeCashSQL = "
UPDATE fyxt_characters
SET
char_money = $newCash
WHERE
idfyxt_character = $charID";
$changeCash = $wpdb->query($changeCashSQL);
$wpdb->print_error();
}
$debugArray = Array();
array_push($debugArray,$charID, $itemID, $buyItem, $getItemDetailsSQL, $getItemDetailsResults,$newItemAdded, $newCash);
echo $debugArray ;
die();
}
?>
I am pretty sure it is 1 (or 2) of 2 things. I am not sure if I am hooking these functions to wordpress right. Or there might be issues with nested functions I have for the jQuery button. I doubt it is number 2 though because it seems to work... I just get a 0 back from the server without any database activity. Here is what the log says.
cID = 112 ?charID=112:538
charMoney = 9990 ?charID=112:539
thisValue = + ?charID=112:540
iID = 664 ?charID=112:541
buy = 0 ?charID=112:542
ajaxurl = http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php ?charID=112:543
data = [object Object] ?charID=112:550
Object {action: "addItemAJAX", charID: 112, itemID: 664, buyItem: 0} ?charID=112:551
XHR finished loading: "http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php". jquery-1.9.1.js:8526
send jquery-1.9.1.js:8526
jQuery.extend.ajax jquery-1.9.1.js:7978
jQuery.(anonymous function) jquery-1.9.1.js:7614
(anonymous function) ?charID=112:554
jQuery.event.dispatch jquery-1.9.1.js:3074
elemData.handle
Thank you very much for all of the help and suggestions!
First of all you need to add hooks in proper way
// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );
// For the users that are logged in:
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
// ajax handler
function addItemAJAX_callback()
{
// code goes here
// since $debugArray is an array, so
die(json_encode($debugArray)); // last line
}
One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.
Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file
add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
// for pluggin, you may use "plugin_dir_url( __FILE__ )"
wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
// Following code will let you use "ajaxObj.ajax_url" to get the
// ajax url (admin-ajax.php) in your my_ajax_scriptjs file
wp_localize_script(
'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
In your my_ajax_script.js file, you may code like this
var data = {
action: 'addItemAJAX_callback',
// ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
// response is an object
// ...
});
Alos remember, when using ajax from admin panel, you don't need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.
I won't go through your code as it seems a bit hard to replicate (see SSCCE for this matter). But I'll outline how to work with Ajax and WordPress (from How to Use AJAX in a WordPress Shortcode?):
1) Enqueue and localize the JavaScript file.
Instead of enqueueing, we could print directly in the head or footer, but it's not good practice. And the localization will pass PHP values to JS in a clean fashion.
I'm assuming you're working with a theme, otherwise change get_stylesheet_directory_uri() to plugins_url().
add_action( 'wp_enqueue_scripts', 'enqueue_so_19721859' );
function enqueue_so_19721859()
{
# jQuery will be loaded as a dependency
## DO NOT use other version than the one bundled with WP
### Things will BREAK if you do so
wp_enqueue_script(
'my-handler',
get_stylesheet_directory_uri() . '/js/ajax.js',
array( 'jquery' )
);
# Here we send PHP values to JS
wp_localize_script(
'my-handler',
'my_handler',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'my_ajax_validation' ) // <--- Security!
)
);
}
2) Ajax for logged and non-logged users
You gotta add a public Ajax callback too with no_priv_:
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
add_action('wp_ajax_no_priv_addItemAJAX', 'addItemAJAX_callback');
3) Ajax Callback and Response
The Ajax callback has security checks and uses wp_send_json_* to handle the response:
function addItemAJAX_callback()
{
check_ajax_referer( 'my_ajax_validation', 'security' );
$my_thing = something();
if( !$my_thing )
wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
else
wp_send_json_success( $my_thing );
}
4) Finally, the script
It's essential to wrap all jQuery with noConflict mode.
You can pass whatever info you need through the localized object my_handler. We check 3 things from the response:
total failure: couldn't reach the callback or didn't pass security
partial failure: the callback was reached but returned json_error
success: proceed with your thing
jQuery( document ).ready( function( $ ) {
var data = {
action: 'addItemAJAX_callback',
security: my_handler.ajaxnonce
};
$( '#my-submit' ).click( function(e) {
e.preventDefault();
$.post(
my_handler.ajaxurl,
data,
function( response ) {
// ERROR HANDLING
if( !response.success ) {
// No data came back, maybe a security error
if( !response.data )
$( '#my-answer' ).html( 'AJAX ERROR: no response' );
else
$( '#my-answer' ).html( response.data.error );
}
else
$( '#my-answer' ).html( response.data );
}
);
});
});
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...