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);
Related
I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>
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).
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>
I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.
After pressing a button, I'm sending the whole HTML content from a webpage (the part within the <html> tags) to a CGI script which manipulates the content and sends it back.
Now I'm trying to replace the existing content with the new one. Unfortunately after assignment, every single <head> or <body> tag (as well as the closing ones) will be killed.
By using some alerts I looked through the returning value as well as the original HTML stuff. Both are absolutely as expected.
But after the assignment there is some magic going on. Please help me to figure out what's going on.
Here is the used JavaScript code I used:
var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);
makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);
function makePOSTRequest(method, url, parameters, htmlNode) {
var http_request = getRequestObj();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function()
{
if (http_request.readyState < 4)
{
var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
document.body.innerHTML = waitingPageBody;
}
else //if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
alert('1response: ' + http_request.responseText);
alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
}//end of if (http_request.status == 200)
else
{//other http statuses
alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
bodyNode.innerHTML = originalBodyInnerHTML;
}
}//end of else if http_request.readyState == 4
}
http_request.open(method, url, true); //async
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function getRequestObj() {
var http_request = false;
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
This is a simple solution that worked for me. Just as a reference.
document.clear();
document.write(newHtml);
where newHtml is the complete html of new web page.
well, with this
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText
you are replacing everything insidee the html, "killing" body, head and everything...
maybe you wanted
document.body.innerHTML = http_request.responseText
Also, I'd use jquery, it makes your life sooo much easier
You cannot do that. It's not possible to replace the contents of the whole html tag. You can get away with replacing only the contents of the body tag. The head element is kind of magical and browser generally don't support replacing it.
If you want to change the whole document, redirect to it.
If you want to change only parts of the head, try sending them in a different form (like JSON), and make appropriate changes using javascript APIs.
Thanks qbeuek for your answer!
To change only the header, Firefox in fact will allow something like this:document.getElementsByTagName('head')[0] += "e.g. some scripts"
But for Internet Explorer it is necessary to add each element separately to the DOM tree.
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script);
However, it is really weird that Firefox behaves like this and not popup with some error...