My current code is:
Play.save = function() {
//Hide the buttons
this.printButton.visible = false;
this.saveButton.visible = false;
this.backButton.visible = false;
//Force the game to re-render.
this.game.cameras.render(); //generally not recommended if you can help it
//Get the canvas information
var img = this.game.stage.canvas.toDataURL("image/octet-stream");
this.saveajax(img);
//Show UI again.
this.printButton.visible = false;
this.saveButton.visible = true;
this.backButton.visible = true;
}
Play.saveajax = function(img){
$.ajax
({
url: "http://localhost/ourthing/character/save.php",
type: "POST",
cache: false,
data: {
img: img
}
});
}
The file 'save.php' works (when i simply open the file). It will execute a query which it has to do. Problem here is: with this script i want to update a user with the given post data (img). But it doesnt execute on this request.
(i create data for var img and send this data to the saveajax function, which will open save.php to execute the query).
Im very new to JS/ajax. Does anyone can help me?
Best regards
apparently I cant comment, so my question is what are you getting on save.php
with command like
error_log(print_r($_REQUEST,true));
I suspect JSON issue here. can we see save.php?
Ok didn't see your previous comment, scrap that - your Jquery is not included.
Answer:
I had to include jQuery:
<script src="assets/js/jquery.js" ></script >
Thanks #Don'tVoteMeDown and #Lixus
Save.php file:
$db = framework::getDBO();
$data = array(
'canvas_character' => $_POST['img'],
);
$db->where('id', 1);
$db->update('ot_users', $data);
(i use my own framework)
Related
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...
I am building a Wordpress site, and using AJAX to load in subsequent pages when the user navigates, so that page transitions are nicely animated.
By default, if you load and inject a page with an embedded Ninja Form, the form simply does not display. There is very little information out there on how to achieve this. I hoped there would be an official out of the box way to get this working, but there doesn't appear to be.
What steps need to be taken in order to get the form to display on the page, when the form has been dynamically loaded with AJAX?
I have experimented with some completely undocumented code samples, and managed to figure it out, along with a few necessary tweaks and additions. I thought I'd share here in case anyone else has difficulty with this.
Step 1. Enqueue necessary JS and CSS
Add the following to your functions.php, because Ninja Forms relies on backbone js, and needs css, which won't be loaded if your initial landing page does not already have a form on it.
add_action('wp_enqueue_scripts', function () {
// enqueue ninja forms css, including for any ninja forms addons
wp_enqueue_style('nf-display', content_url('/plugins/ninja-forms/assets/css/display-structure.css'), ['dashicons'], core_dev_version(''));
wp_enqueue_style('nf-layout-front-end', content_url('/plugins/ninja-forms-style/layouts/assets/css/display-structure.css'), ['nf-display'], core_dev_version(''));
// make sure that backbone is enqueued on the page, as ninja forms relies on this
wp_enqueue_script('backbone');
}, 100);
.
Step 2. Add an AJAX function that returns the form data
You shouldn't need to edit this, just add it to your functions.php. The javascript we use in step 3 will make its own AJAX call to request some form data in a very specific format.
add_action('init', function () {
// if this is not an AJAX form request, return
if (! isset($_REQUEST[ 'async_form' ])) {
return;
}
// clear default loaded scripts.
global $wp_scripts;
unset($wp_scripts->registered);
// get the requested form id
$form_id = absint($_REQUEST['async_form']);
// retrieve the requested form
ob_start();
$form = do_shortcode("[ninja_forms id='{$form_id}']");
ob_get_clean();
// output the requested form on the page
ob_start();
NF_Display_Render::output_templates();
$templates = ob_get_clean();
$response = [
'form' => $form,
'scripts' => $wp_scripts->registered,
'templates' => $templates
];
echo json_encode($response);
// die, because we don't want anything else to be returned
die();
});
.
Step 3. Add JS helper functions to your landing page
This simply adds some helpful JS code into your site.
You can add this to functions.php as is, or include it in a separate JS file.
This is what we will use to load and initialise the form we want.
add_action('wp_footer', function () {
// adds a script to the footer
?>
<script type="text/javascript">
var NinjaFormsAsyncForm = function(formID, targetContainer) {
this.formID = formID;
this.targetContainer = targetContainer;
this.formHTML;
this.formTemplates;
this.formScripts;
this.fetch = function(callback) {
jQuery.post('/', { async_form: this.formID }, this.fetchHandler.bind(this))
.then(callback);
}
this.fetchHandler = function(response) {
response = JSON.parse( response );
window.nfFrontEnd = window.nfFrontEnd || response.nfFrontEnd;
window.nfi18n = window.nfi18n || response.nfi18n || {};
this.formHTML = response.form;
this.formTemplates = response.templates;
this.formScripts = response.scripts;
}
this.load = function() {
this.loadFormHTML(this.formHTML, this.targetContainer);
this.loadTemplates(this.formTemplates);
this.loadScripts(this.formScripts);
}
this.loadFormHTML = function(form, targetContainer) {
jQuery(targetContainer).append( form );
}
this.loadTemplates = function(templates) {
document.body.innerHTML += templates;
}
this.loadScripts = function(scripts) {
jQuery.each( scripts, function( nfScript ){
var script = document.createElement('script');
// note that eval() can be dangerous to use - do your research
eval( scripts[nfScript].extra.data );
window.nfFrontEnd = window.nfFrontEnd || nfFrontEnd;
script.setAttribute('src',scripts[nfScript].src);
var appendChild = document.head.appendChild(script);
});
}
this.remove = function() {
jQuery(this.targetContainer).empty();
}
}
</script>
<?php
}, 100);
.
Step 4. Initialise the form after you AJAX in your page
I can't tell you how to AJAX in your pages - that's a whole other topic for you to figure out.
But, once you have loaded your page content with included Ninja Form, and once that has successfully been on the page, now you need to initialise the form.
This uses the javascript helper (step 3), which in turn calls the php helper (step 2), and finally displays the form on your page!
You'll need to know the ID of the form that's been injected. My tactic was to include this as a data-attribute in my page markup.
var form_id = 1;
var asyncForm = new NinjaFormsAsyncForm(form_id, '.ninja-forms-dynamic');
asyncForm.fetch(function () {
asyncForm.load();
});
And that's about all there is to it!
Hopefully this may save others the time and effort of figuring all of this out.
I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();
NOTE: There are a lot of details here, so if anyone needs a condensed version of this, I'm happy to summarize.
I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
I know that this function works. I am trying to access this function in my Javascript with:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The section in my javascript...
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
... is a block loop and will loop through the block variable, vehicle_makes, set in the PHP function. This works upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the PHP runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the HTML. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
This is the bit of code in the php that reads the $_POST, and call the php function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. I've checked the network tab and console tab, and have done multiple tests to confirm that. It appears that the block variable is not being set. Is what I'm trying to do even possible? I have a feeling that to get this answer, we'll need to know more about phpBB's template engine, and how it works with these template variable. Also, just to clarify, I think the term 'template variable' is specific to phpBB. It's the term they use for variables set in PHP, to be accessed by the HTML, and javascript files. This works through a phpBB class called 'template', and a function called 'assign_block_vars'. I don't know exactly how that work.
If anyone has done this for phpBB, or has any ideas, I would appreciate it.
Think I found the problem. At the beginning of my PHP, I have an include statement to include the PHP file containing the class for connecting to the database. In the statement $result = $db->sql_query($sql);, $db is set in this other PHP file. I don't entirely understand, but because of that, $db was outside of the scope of my function get_vehicle_makes(). I had to create a class inside my PHP file, and pass $db as a parameter to the function using:
class vehicle {
public function __construct($db)
{
$this->db = $db;
}
function get_vehicle_makes()
{
$sql = 'SELECT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $this->db->sql_query($sql);
Hope this helps.
I have a star rating system on my application - the following code works correctly if it is in the PHP doc. But when I remove it and place it in a js file, it doesn't work.
Could someone please let me know why it's not working when i call the js file. Thanks.
<script>
$(document).ready(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var rating = $(this).attr('id');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var rating = $(this).attr('id');
var dataRate = 'act=rate&app_id=<?php echo $app_id; ?>&id=<?php echo $id; ?>&rate='+rating;
$('.rate-btn').removeClass('rate-btn-active');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-active');
};
$.ajax({
type : "POST",
url : "submitRating.php", // I have tried changing this to reflect the directory
data: dataRate,
success:function(){}
});
});
});
</script>
What "TamilSelvan" said is right you can't inject php code in js file. Try keeping the app_id and id in webstorage (or cookies) if you are redirection from some other page to this page and then make use of them in js file else first make AJAX call to retrieve app_id and id then use them.