I am having a problem with calling 2 separate ajax functions. I have a loop that loops through all checkbox elements on the page then if they are checked it calls an ajax function that moves some data in my database. Then outside of the for loop i call another ajax function that goes to my database and pulls the results back to my ID element. I have had to name my httprequests differently so they dont fight, Both functions work but the one outside my loop goes to fast and doesnt pull the new/changed data. If i put an alert before this outside loop function it then works. I have also tried to use a setTimeout(myFunctio(), 3000) with no luck.
Here is my code.
function ungroupContact(){
group = document.getElementsByName("moveGroup")[0].value;
for(i=0;i<=25;i++){
if(document.getElementById('checkBox'+i)){
if(document.getElementById('checkBox'+i).checked){
var email = document.getElementById('checkBox'+i).value;
moveContact(email, group);
}
}
}
//alert("hello");
//setTimeout(alert("hello"),12000);
groupList1(group);
}
This is my first time posting, sorry if this is noobish, currently studying my degree in computer science.
Thanks for any suggestion and/or help
Sorry i should have known to put up the ajax functions. I have used the layout from w3schools.
function moveContact(email, group){
if (email=="" || group=="")
{
document.getElementById("sidebar2").innerHTML="Something wrong was entered";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
if (xmlhttp1.readyState==1 || xmlhttp1.readyState==2 || xmlhttp1.readyState==3)
{
document.getElementById("sidebar2").innerHTML="<img src='images/loading.gif' alt='Loading'> ";
}
if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
{
document.getElementById("sidebar2").innerHTML=xmlhttp1.responseText;
}
}
xmlhttp1.open("GET","core/moveContact.php?group="+group+"&email="+email,true);
xmlhttp1.send();
return;
}
You will need to keep track of when the last moveContact() asynchronous ajax function is done and then (and only then), call groupList1().
Since you have not disclosed the moveContact() code where the ajax calls are probably being done, we can't really recommend specifics on tracking them. One simple technique is to set up a counter of pending ajax calls and in each success handler for the moveContact() ajax calls, check to see if the counter has now reached zero. If so, you can then call groupList1(group).
Assuming you added a completion callback to moveContact(), you could do it like this:
function ungroupContact(){
group = document.getElementsByName("moveGroup")[0].value;
var contactsRemaining = 0;
for(i=0;i<=25;i++){
if(document.getElementById('checkBox'+i)){
if(document.getElementById('checkBox'+i).checked){
++contactsRemaining;
var email = document.getElementById('checkBox'+i).value;
moveContact(email, group, function() {
--contactsRemaining;
if (contactsRemaining === 0) {
groupList1(group);
}
});
}
}
}
}
function moveContact(email, group, fn){
if (email=="" || group=="") {
document.getElementById("sidebar2").innerHTML="Something wrong was entered";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==1 || xmlhttp1.readyState==2 || xmlhttp1.readyState==3) {
document.getElementById("sidebar2").innerHTML="<img src='images/loading.gif' alt='Loading'> ";
}
if (xmlhttp1.readyState==4 && xmlhttp1.status==200) {
document.getElementById("sidebar2").innerHTML=xmlhttp1.responseText;
// we are done now, so call the finish callback
if (fn) {
fn();
}
}
}
xmlhttp1.open("GET","core/moveContact.php?group="+group+"&email="+email,true);
xmlhttp1.send();
return;
}
You can add callback function on success and in that function execute groupList1 function when all methods finish executing:
var finished = 0;
moveContact(email, group, function() {
if (++finished == 25) {
groupList1(group);
}
});
Related
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);
With this function:
function start() {
MONDUX();
Biggie();
}
function MONDUX executes, and the AJAX call returns good data and is displayed correctly.
However, Biggie() is a.w.a.l.
The result of this :
function start() {
Biggie();
MONDUX();
}
is the opposite. Biggie() works as expected, MONUX() fails.
This doesn't do any good, down in the body:
<script type="text/JavaScript">
window.onload= start();
</script>
and, this dodge is not helpful:
<body onload="start()">
and that was tried like so also
Detest cargo~cult programming and running out of ideas here. Suggestions?
These resources were all related // near hits // no cigar.
Loading javascript in body onload with 2 functions
JS and Body(Window) Onload event
JavaScript: How is "function onload() {}" different from "onload = function() {}"? That one
was fascinating but way deep waters for me...
How to onload two javascript files? meh... good, but...
?? :/~
<script type="text/javascript" >
function MONDUX(){
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("WhatThexBobby").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS 22solo PHP.php?figure1=5&figure2=33", true);
xmlhttp.send();
alert(WhatThexBobby);
}
</script>
<script type="text/javascript" >
function Biggie(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("FreakinEh").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS solo PHP.php?figure1=5&figure2=10", true);
xmlhttp.send();
alert(FreakinEh);
}
</script>
You're assigning the request to the global variable xmlhttp, and then reassigning that variable to another request before the first one has returned. I don't know if that is causing your problem, but it's definitely going to cause a problem. It's also very bad JavaScript practice.
Simple fix is to put the line 'var xmlhttp;' at the beginning of both functions.
Edit: Just in case you didn't know this: xmlhttprequest is asynchronous. You call 'send', and your remaining statements in the script and document continue to run while the request is being sent to the server. Only after the server returns do the various callback methods (onreadystatechange, and the like) get called, and this is long after your alerts were shown.
Considering one of them is throwing some error, would it not be good idea to put them in Try Catch ? Something like,
function start() {
try
{
MONDUX();
}
catch(err)
{
// handle error
}
try
{
Biggie();
}
catch(err)
{
//Handle error
}
finally
{
// cleanup
}
}
This will ensure both runs even if one of them mis-fires.
I have a simple script that i am testing with, but its acting very odd. I call a script which loads and i have it to a particular td id, I then call a second script and add that to different td id but for some reason it wipes out the first div's content even though they are seperate.
This is what i have:
function call_back(result,div_id,func){
document.getElementById(div_id).innerHTML = result;
if(typeof(func) != 'undefined'){func();}
}
function caller(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function call_file(url,div_id,func){
caller(url,function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
call_back(xmlhttp.responseText,div_id,func);
}
});
}
I then have this on my onload:
window.onload = function(){
stage = 6;
call_file('test.html','menu_left');
switch(parseInt(stage)){
case 6: call_file('test2.html','main'); break;
}
};
The problem arises with the case statement. If i remove the case statement the contents added with test.html loads fine, but if i add the case statement, content from test.html disappears and then only test2.html displays.
The html for the id's are:
<table class="body_wrapper">
<tr>
<td class="menu_left" id="menu_left"></td>
<td class="main" id="main"></td>
</tr>
</table>
Why might this be happening?
The problem has nothing to do with the switch statement. As you are calling the ajax request for some local files and it is already cached, the call_back function is called twice before document.getElementById(div_id).innerHTML = result; executes and hence replaced by the variable values from the last call. If you just put an alert into the call_back function like below
function call_back(result, div_id, func) {
alert(result);
document.getElementById(div_id).innerHTML = result;
if (typeof (func) != 'undefined') { func(); }
}
you will find it is working. But as it is not a solution, alternatively if you modify this
xmlhttp.open("GET", url, true);
to
xmlhttp.open("GET", url, false);
it will work but you will loose the asynchronous feature of AJAX.
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
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>