I have written a small JavaScript function which will perform an Ajax request every x amount of seconds.
I was hoping some of you could give it a look over and give me any pointers on redundant code or bad practice.
The idea of the function is to:
1) Allow for polling to be initiated
2) Once initiated, poll once every x seconds and perform an ajax request.
3) Stop polling once disablePolling() is run.
Here is the code:
requester.js
function Request() {
this.poll = false;
this.activatePoll = function () {
this.poll = true;
this.runPoll();
};
this.disablePoll = function () {
this.poll = false;
};
this.runPoll = function () {
var self = this;
var poll = setTimeout(function () {
$.ajax({
url: './request.php',
success: function (response) {
console.log(response);
},
dataType: "json",
complete: function () {
if (self.poll == false) {
clearTimeout(poll);
} else {
self.runPoll();
}
}
})
}, 1000);
};
}
For anyone else which wants to run the code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Requester</title>
</head>
<body>
<h1>Requester</h1>
<div id="requester">
<input type="button" onclick="$request.test();" value="test">
<input type="button" onclick="$request.activatePoll();" value="poll">
<input type="button" onclick="$request.disablePoll();" value="turn off poll">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="js/request.js"></script>
<script>
$(document).ready(function () {
$request = new Request();
});
</script>
</html>
request.php
<?php
echo json_encode($time());
?>
Thank you.
Related
I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>
The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)
Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>
I making my own real time youtube subscriber counter but refresh time is to high and when I change refresh time it not happening. Can someone tell me what I am doing wrong?
<html>
<head>
<link rel="stylesheet" href="odometer-theme-default.css"/>
<script src="odometer.js"></script>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<style>
.odometer {
font-size:100px;
}
#ytName {
font-size: 52px;
font-family:Arial;
}
</style>
</head>
<script type="text/javascript">
$(document).ready( function() {
var chanName = "";
loadChannel("UCPKqr9qSEXi6r03B18wRj6g");
function loadChannel(name) {
chanName = name;
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+name+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url1, function(data) {
$('#ytName').html(data.items[0].snippet.title);
$('#ytLink').html('Link');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
}, 1000);
});
});
</script>
<body background = "bg.jpg">
<center>
<div id="ytName"></div>
<div id="ytLink"></div>
<div id="odometer" class="odometer"></div>
</center>
</body>
Maybe javascript should be written differently?
if you write the new time in milliseconds, the response is a bit
setInterval( function() {
// update code is here
}, 1000)
I'm getting "Uncaught ReferenceError: refreshAgonas is not defined "
The players div is filled correctly. Do I need some kind of special define with the JS functions in the JS file?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-draw.js"></script>
<h2>Game</h2>
<div class="agonas">
<script>
setInterval(refreshAgonas, 5000);
var inRequesG = false;
</script>
</div>
<h2>Players</h2>
<div class="players">
<script>
setInterval(refreshPlayers, 5000);
var inRequest = false;
</script>
</div>
</html>
jquery-draw.js
function refreshPlayers() {
if (inRequest) {
return false;
}
inRequest = true;
var load = $.get('playersdata.php');
$(".players").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".players").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".players").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequest = false;
});
}
function refreshAgonas() {
if (inRequestG) {
return false;
}
inRequestG = true;
var load = $.get('playersdata.php');
$(".agonas").html('Refreshing');
load.error(function () {
console.log("Mlkia kaneis");
$(".agonas").html('failed to load');
// do something here if request failed
});
load.success(function (res) {
console.log("Success");
$(".agonas").html('<table border="1"><tr><th>ID</th><th>Name</th><th>Email</th><th>League</th><th>Sex</th><th>Birthday</th></tr>' + res + '</table>');
});
load.done(function () {
console.log("Completed");
inRequestG = false;
});
}
Now I saw the problem:
Replace
var inRequesG = false;
With
var inRequestG = false;
You forgot the "t"
Try defining the functions like this:
var refreshPlayers = function () {};
var refreshAgonas = function () {};
Try this and respond with the results.
EDIT: didn't mean to include the parenthesis.
Try replacing:
setInterval( refreshAgonas, 5000);
With this:
setInterval(function(){ refreshAgonas()}, 5000);
i am try to get latitude and longitude value from ip address
after getting lat and lng value POST in to php file using AJAX and generate new xml file
this is my html file:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function getlg(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
$.ajax({
type: "POST",
url: "http://localhost/SVN/trunk/home/url.php?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val(),
contentType: "text/html",
success: function(token) {
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
}
</script>
<body>
<div id="region"><h5></h5></div>
Enter Radius: <input type="text" id="radius1"></input>
<input type="button" id="filter"onclick="getlg()" value="Go">
</body>
</head>
</html>
this is my php file:-
<?php
function convertNodeValueChars($node) {
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType == XML_TEXT_NODE) {
$childNode->nodeValue = iconv('utf-8', 'ascii//TRANSLIT', $childNode->nodeValue);
}
convertNodeValueChars($childNode);
}
}
}
$url='http://services.gisgraphy.com/geoloc/search?lat='.$_GET['lat'].'&lng='.$_GET['lng'].'&radius='.$_GET['radius'];
$doc = new DOMDocument();
$doc->load($url);
$doc->save('General.xml');
?>
in this file i am try to Get lat and long and radius from html ajax function and getting one new xml file with help of url.
but its take so much time if radius is biggest.
i want to try this php code in java script dont like server side scripting.
please help me out with this...
thanks...
try this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
var location = "http://services.gisgraphy.com/geoloc/search?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val();
document.write('Link text');
}
</script>
<body>
<div id="region"><h5></h5></div>
<input type="text" id="radius1" onchange="myFunction()"></input>
</body>
</head>
what's wrong here?
OPTIONS https://twitter.com/oauth/request_token 401 (Unauthorized)
jsOAuth-1.3.4.js:483 XMLHttpRequest cannot load
https://twitter.com/oauth/request_token. Origin "http://localhost:8080"
is not allowed by Access-Control-Allow-Origin.Object
<!DOCTYPE html>
<html>
<head>
<!--
A simple example of PIN-based oauth flow with Twitter and jsOAuth.
This is mostly based on/copied from <http://log.coffeesounds.com/oauth-and-pin-based-authorization-in-javascri>.
Get jsOAuth at <https://github.com/bytespider/jsOAuth/downloads>
-->
<meta charset="utf-8">
<title>jsOauth test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jsOAuth-1.3.4.js"></script>
<style type="text/css" media="screen">
</style>
<script>
$(document).ready(function() {
var options = {
consumerKey: 'YOUR_CONSUMER_KEY',
consumerSecret: 'YOUR_CONSUMER_SECRET'
};
var requestParams;
var accessParams;
var oauth = OAuth(options);
oauth.get('https://twitter.com/oauth/request_token',
function(data) {
console.dir(data);
window.open('https://twitter.com/oauth/authorize?'+data.text);
requestParams = data.text
},
function(data) { alert('darn'); console.dir(data) }
);
$('#pinbutton').click(function() {
if ($('#pin').val()) {
oauth.get('https://twitter.com/oauth/access_token?oauth_verifier='+$('#pin').val()+'&'+requestParams,
function(data) {
console.dir(data);
// split the query string as needed
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {;
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
};
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
getHomeTimeline();
},
function(data) { alert('poop'); console.dir(data); }
);
}
});
function getHomeTimeline() {
oauth.get('https://api.twitter.com/1/statuses/home_timeline.json',
function(data) {
entries = JSON.parse(data.text);
var html = [];
for (var i = 0; i < entries.length; i++) {
html.push(JSON.stringify(entries[i]));
};
$('#timeline').html(html.join('<hr>'));
},
function(data) { alert('lame'); console.dir(data); }
);
}
});
</script>
</head>
<body>
<h1>jsOauth test</h1>
When you get a PIN, enter it here.
<input id="pin" type="text" value=""><button id='pinbutton'>Save</button>
<div id="timeline">
</div>
</body>
</html>
I could give you the answer, but what you're doing is against the Twitter API Terms of Service. OAuthing in JavaScript exposes the secret credentials to anyone who visits the site and that is A Bad Thing. Please do this on your back-end.