XMLHttpRequest leak - javascript

Below is my javascript code snippet. Its not running as expected, please help me with this.
<script type="text/javascript">
function getCurrentLocation() {
console.log("inside location");
navigator.geolocation.getCurrentPosition(function(position) {
insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
}
function insert_coord(loc) {
var request = new XMLHttpRequest();
request.open("POST","start.php",true);
request.onreadystatechange = function() {
callback(request);
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));
return request;
}
function callback(req) {
console.log("inside callback");
if(req.readyState == 4)
if(req.status == 200) {
document.getElementById("scratch").innerHTML = "callback success";
//window.setTimeout("getCurrentLocation()",5000);
setTimeout(getCurrentLocation,5000);
}
}
getCurrentLocation(); //called on body load
</script>
What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals.
Here's the firebug screenshot:
IS there a leak in the program. please help.
EDIT: The expected outcome in the firebug console should be like this :-
inside location
POST ....
inside callback
/* 5 secs later */
inside location
POST ...
inside callback
/* keep repeating */

Probably not the problem, but I can suggest two refactorings:
Merge your two conditions in callback():
if ((req.readyState == 4) && (req.status == 200)) {
And you can shorten your setTimeout line to:
setTimeout(getCurrentLocation, 5000);
And in an effort to fix the problem, can I get you to remove the setTimeout() from callback(), and replace the call to getCurrentLocation() with it? So you're only writing "callback success" when the callback is run, nothing else.
setTimeout(getCurrentLocation, 5000); //called on body load

Related

Javascript include file and refresh every 30 seconds

I have 3 files i refer to them as:
$nowplaying = file_get_contents("/api/static/nowplaying");
$dj = file_get_contents("/api/static/dj");
$listeners = file_get_contents("/api/static/listeners");
I want to call them in my php file inside div tags by using
'.$dj.'
'.$nowplaying.'
'.$listeners.'
but the contents of the files i am pulling update every 30 seconds so I need to refresh the data shown without refreshing the page. I'm thinking javascript jquery may be the one but i'm not too familiar with it.
Many thanks!
If you have jQuery
setInterval(function(){
$.get("/api/static/nowplaying",function(data){
// Do something with data
});
},30000);
with javascript kinda like
var request = new XMLHttpRequest();
setInterval(function(){
request.open('GET', '/api/static/nowplaying', true);
request.send();
},30000)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
Yes, I think using jquery/JavaScript is what you are looking for and its pretty simple. Just use the setInterval() method in JavaScript to have it repeatedly run a function on a schedule. Since you're rather new to this I'll try to make a simple example. The code below runs updateDiv() every 30 seconds.
<script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js">
</script>
<script type='text/javascript'>
var myVar
function updateDiv(){
clearInterval(myVar);
alert('your code should go here');
myVar = setInterval("updateDiv()", 30000);
}
$(document).ready(function(){
myVar = setInterval("updateDiv()", 30000);
});
You can view this here: https://jsfiddle.net/jglazer63/h6q20dj9/1/

Control skips the ajax object onreadystatechange function. why?

I'm new to web-development. Created a signup page making some asynchronous calls to php. Ran debugging found the control skips the onreadystatechange function completely. Please help...
var ajax = ajaxObj("POST", "signup.php"); //defines the ajax object, definition is below
ajax.onreadystatechange = function () { //doesn't run after this line
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box
at <u>"+e+"</u> in a moment to complete the sign up process.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); //control reaches here directly
}
}// control exits here
The ajax object is created externally here..
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is because it's an event callback function and it will be called when server responds to your ajax request. If you're using firefox press F12, switch to network tab and check html and xhr to see it's status.
Because it is asynchronous so the function won't be called as you step through the code in a linear fashion.
It gets called by native code when the ready state changes.
Stick a breakpoint inside the function if you want to debug it.

Ajax - browser lag when updating content

I'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).

Turning an OnClick Event Into A Timed Event with JavaScript & AJAX

Im currently in the learning process with AJAX & JavaScript..
I have a quick question to the wise..
How can i turn the code below into a timed event instead of an OnClick event.
**For Example i would like to refresh the "showlist" DIV every 5 seconds...
I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..
I am trying to slowly understand the basics :)
Any guidance would be greatly appreciated
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showlist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>
</html>
You can change loadXMLDoc function to make use of setTimeout. Consider this example:
function loadXMLDoc() {
var xmlhttp,
timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showlist").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.onerror = function() {
clearTimeout(timer);
};
xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
xmlhttp.send();
timer = setTimeout(loadXMLDoc, 5000);
}
Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.
I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.
Maybe you can re-use my code?
// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
if(i > (totalPics - 1)){
i = 0;
}
myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).
So what you need to do, is refresh the array when you got new item in your showlist.
This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:
(function doMeSelf(){
setTimeout(function(){
loadXMLDoc();
doMeSelf();
},5000);
})();
Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.
See this question for some background: What do parentheses surrounding a object/function/class declaration mean?

Ajax, call multiple PHP function from a single js

i have a trouble with my project.
In my site i have a page html with a single button and at onclick() eventa js function call intro.js, trough a XmlHttpRequestObject have to do many calls at many php function, in detail:
in js i call scan() function
function scan() {
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp.open("GET", "php/intro.php?P1=http://"+oStxt.value, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
// change cursor to "busy" hourglass icon
document.body.style.cursor = "wait";
}
// display the error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
And in handleRequestStatuschange i have:
function handleRequestStateChange()
{
// obtain a reference to the <div> element on the page
// display the status of the request
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
// read response only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// read the message from the server
response = xmlHttp.responseText;
// display the message
document.body.appendChild(oRtag);
oPch = document.getElementById("divRtag");
oOch = document.createTextNode(response);
oPch.appendChild(oOch);
}
catch(e)
{
// display error message
alert("Error reading the response: " + e.toString());
}
}
else
{
// display status message
alert("There was a problem retrieving the data:\n" +
xmlHttp.statusText);
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
It works for just one php call, but i need to call different php page in scan function after intro.php (scan2.php, scan3.php, ecc ecc) and with json_decode write single data of the array that return in div tags on my html page.
Which is the best way to call different php pages and manage the results with a single js function in ajax?
Thanks in advance
Alessandro
Not sure how you built your php-functions. Cant you create a function, that calls other functions (scans)?
function doScan(){
$data = array();
//like this, or with a loop
$data['scan1'] = scan1();
....
$data['scanN'] = scanN();
echo json_encode($data);
}
Really, the simplest method that comes to mind is just to parameterise this function. This is as simple as
function doScan(url) { // Code here }
Then simply make the exact same ajax request with the url variable.
xmlHttp.open("GET", "php/" + url + "?P1=http://"+oStxt.value, true);
Next, simply call the doScan function with various parameters.
doScan("index.php");
doScan("otherPage.php");
doScan("somethingElse.php");
This will make ajax requests on the PHP file that you specify.

Categories