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

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?

Related

What causes a function to "freeze" in javascript?

Say in window.onload function i call a bunch of other methods:
function window.onload(){
method1();
alert("test1");
method2();
alert("test2");
}
So my test1 method is working fine, i get the alert "test1", but then it appears that my code is "freezing" on method2, so the alert "test2" is not being called.
Here is what my test2 method looks like
function method2(){
alert("testing");
var xhr = new XMLHttpRequest();
xhr.open("GET", "url that i want to call from", true);
xhr.onload = function() {
if (xhr.status==200) {
alert(xhr.responseText);
alert("yay");
}
else{
alert("Aww");
}
}
xhr.send();
}
what i dont understand is why i dont even get the alert "testing", if my code is freezing somewhere why doesnt it at least run the first line in the method?
Can anyone explain why this occurs in javascript?
thanks
I have always hooked into to the 'on ready state change' event.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
$(document).ready(function () {
loadDoc();
});
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
alert("yay");
}
};
xhttp.open("GET", "demo", true);
xhttp.send();
}
</script>
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
From the information you provided, I am guessing that you are running into browser security issues ...
I would recommend using jquery to handle the job for you. the $(document).ready function in jquery has always worked awesomely for me in the years I have been using the framework.
If you can't use jquery, then you need to have the user click on a button in order to initiate the http request you desire.
Also, if you need to perform the 'Awww' action you can append it to the if statement but I would recommend using if else based on xhttp.readyState values or your 'Awww' will repeat often.

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).

jQuery - load data to variable, check data and update in DIV

I make very, very simple intranet chat. I load every 2 sec data from URL to DIV. But I want (and I don't know how) load data to variable, compare data from DIV and if !=, update in DIV. And scroll to down "page" in this DIV. Please, help me stackoverflowers! :)
var chatInterval;
function chatLoad(){
chatInterval = setInterval(function(){
$('#chat-conversations').load('/AJAX/Chat.app');
}, 2000);
}
Instead of just loading it directly put it on a variable first and compare it. That's why I use .get instead of .load, .load loads the content directly into the element.
var chatInterval;
var chatContent = "";
function chatLoad(){
chatInterval = setInterval(function(){
$.get('/AJAX/Chat.app',function(data){
if(data!=chatContent){
$('#chat-conversations').html(data);
chatContent = data;
}
})
}, 2000);
}
First of all you must understand that compare all data is bad idea, you just need check that user have new messages whatever.
Also you must now about long polling and short polling good explanation.
Why its bad idea to compare all data?
Because after a 5 minutes you will receive a BIG BIG bunch of data (performance).
Hor compare if you want:
var _current_data = null;
var interval = setInterval(function(){
// your logic to receive data, we receive response from server
if(!_current_data) _current_data = response;
else if(_current_data != response){
// Render logic (insert data into html tags and return html as string)
$("div").html(render(current_data));
}
}, 2000);
You can use ajax to get the latest posts without reloading the page as you said with the interval of 2 second.
function getXmlHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
// code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// code for IE5 and IE6
}
else {
alert("Browser doesn't support Ajax..!!");
}
return xmlhttp;
}
function loadData() {
xmlhttp = getXmlHttpRequest();
if (xmlhttp !== null) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState < 4) {
document.getElementById('your-div').innerHTML = "<img src = 'loader-animation.gif'/>";
}
else if (xmlhttp.readyState === 4) {
var res = xmlhttp.responseText;
if (res.trim() !== "error") {
document.getElementById('your-div').innerHTML = res;
} else {
document.getElementById('your-div').innerHTML = "<img src = 'error.png' style='vertical-align:middle;'/>";
}
}
}
xmlhttp.open("POST", "data_loading_page.php", true);
xmlhttp.send(null);
}
}
on data_loading_page.php (any media of you use php or jsp or anything) print your posts using a while. so whenever the function calls the php page then you'll get the updates;
call the script by
setInterval(function() {
loadData();
}, 2000);

How do I use ajax to auto refresh a section of page without manually invoking a function within javascript?

var xmlhttp;
//Set up ajax first so he knows which guy to play with
function loadXMLDoc(url,cfunc)
{
//Code to catch modern browsers
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//Code to catch crap browsers
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//Set up
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
//Set a function to deploy when something calls myFunction()
function myFunction()
{
loadXMLDoc("../../../support/ajaxTest.txt",function()
{
//Fires off when button pressed
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText;
setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 );
}
});
}
I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
function autoRefresh()
{
var url = "../../../support/ajaxTest.txt";
var target = document.getElementById("statusRefresh");
var doRefresh = function()
{
loadXMLDoc(url, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
target.innerHTML=xmlhttp.responseText;
}
}
});
setInterval( doRefresh, 5000 );
}
and
document.onload = autoRefresh;
more information is needed such as what is your goal, what do you currently have......what are you trying to do......If its a script thats triggered by something from example a user viewing your page or click a button then use that button to triiger the function to auto refresh
Another way is to use a crob job

How make ajax update every (n) number of seconds with out using jquery but using javascript?

I'm trying to hava a javascript poll the server every (n) number of seconds how would I do this with javascript?
Assuming you are using jQuery:
var seconds = 5;
setInterval(function(){
$.ajax({
url: 'something.something',
data: 'something'
});
}, seconds * 1000)
Without jQuery:
var seconds = 5;
setInterval(function(){
some_ajax_function();
}, seconds * 1000)
Or as #Felix suggests below:
var seconds = 5;
some_ajax_function(seconds);
function some_ajax_function(seconds){
..ajax
onsuccess: setTimeout(function(){some_ajax_function(seconds);},
seconds * 1000)
}
It is simple with the following function
window.setInterval("yourfunctionWithAjaxRequestETC", time_in_ms);});
Enjoy :)
first, we need to make our ajax request object. We need to take different browsers into account.
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Now, we'll write our function to send a request
function askData(){
xmlhttp.open("GET","myinfosource.php",true); // opens a Get request to the url myinfosource.php, and sets the request to asynchronuous.
xmlhttp.send(); //sends the request
}
Now, let's write an event handler that changes the HTML when the info comes back.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) //if we reveived data (readystate 4 means that information was received. status 200 is the status of the HTTP request, where 200 means 'ok'.
{
//insert data into the div you want.
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And finally, we set an interval on the first function we wrote to make it run every x seconds.
setInterval('askData',10000);
this will refresh your data.
I hope you see now why most people use a framework such as jquery to use AJAX. One of the major advantages of js frameworks is that they work around browser incompatibilities so that you, as the developer can concentrate on the task at hand.
I assume that there is a servlet with URL Pattern /UpdateCount is configured in web.xml to provide dynamic data/content and there is a div element countStatDiv in the jsp page.
The following code refreshes/updates the content of countStatDiv at every 30 seconds using GET method and variable seconds value can be changed according to the need:
<script>
var request;
var seconds=30;
function getRequestObject(){
setInterval(function() {sendRequest();},seconds*1000);
if (window.ActiveXObject){
return (new ActiveXObject("Microsoft.XMLHTTP"));
} else if (window.XMLHttpRequest){
return(new XMLHttpRequest());
} else {
return (null);
}
}
function sendRequest(){
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET", "../UpdateCount", true);
request.send(null);
}
function handleResponse(){
if((request.readyState == 4)&&(request.status == 200)){
var serverResponse = request.responseText;
var statCtrl=document.getElementById("countStatDiv");
statCtrl.innerHTML=serverResponse;
}
}
</script>

Categories