I need to send request to server in sync mode, so i set async=false, but i receive always NETWORK_ERR: XMLHttpRequest Exception 101. Here is my code, there i someone that know how can i improve it to fix this issue?
var request = new XMLHttpRequest();
request.open("GET", 'ip-address ', false);
request.onreadystatechange = function () {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var data = JSON.parse(request.responseText);
var object = "";
var string = "";
var find = false;
window.localStorage.setItem(data.id, JSON.stringify(data));
$.each(data.img, function (i, item) {
if (data.img[i].principal) {
string = data.img[i].path;
}
});
if (string == "") string = data.img[0].path;
var splitt = string.substring(2);
window.localStorage.setItem("img" + data.id, splitt);
if ($("#img" + (l + 1)).attr("src") === 'ip-address' + splitt) {
find = true;
} else {
object='<img id="img'+(l+1)+'" src="ip-address'+splitt+'" name="'+data.id+'"></img>'; if (!trovata) {
if (flag) {
$("#" + (l + 1)).empty();
$("#" + (l + 1)).html(object);
if (l == 0) {
$("#" + (l + 1)).flip({
direction: 'tb'
});
} else {
switch (l % 2) {
case (1):
$("#" + (l + 1)).flip({
direction: 'lr'
});
break;
case (0):
$("# " + (l + 1)).flip({
direction: 'rl'
});
break;
}
}
}
}
}
}
}
request.send();
Related
in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know
got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```
I have a javascript which parse the server data and stores it in a variable. I can use that variable only in one function but not in multiple functions, please find the javascript code below.
function serverData(command, param) {
console.log('command is ' + command + ' param is ' + param);
if (!command) {
console.log('Command not recieved, No call to Server');
return;
}
var url = 'ProgramSetting.cgi?command=' + command;
if (param) {
url += '&' + param;
}
var xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
responseHandler(command, data);
}
};
}
function responseHandler(command, jsonData) {
if (!jsonData) {
console.log('Json from server not defined!!!');
return;
}
switch (command) {
case 'set':
if (jsonData.result == 'success') {
document.getElementById('info').innerHTML = 'INFO: Committed successfully!';
} else {
if (jsonData.options && jsonData.options.length > 0) {
var failedOptions = '';
for (var i = 0; i < jsonData.options.length; i++) {
failedOptions += ' ' + jsonData.options[i];
}
document.getElementById('info').innerHTML =
'ERROR: Failed to commit following option(s)-' + failedOptions;
} else {
console.log('Failed to Commit');
document.getElementById('info').innerHTML = 'ERROR: Failed to Commit';
}
initialPageLoad();
document.getElementById('info').style.color = 'red';
}
break;
case 'get':
console.log('jsonData.POLICY is ' + jsonData.POLICY);
if (jsonData.POLICY == 'gehc') {
document.getElementById('list1').checked = true;
gehc();
} else if (jsonData.POLICY == 'strict') {
document.getElementById('list2').checked = true;
strictgehc();
} else if (jsonData.POLICY == 'custom') {
document.getElementById('list3').checked = true;
custom(jsonData);
}
break;
default:
console.log("we don't support this");
}
}
function custom(jsonData) {
console.log('Custom called');
console.log('jsonData.MINLEN_RANGE is ' + jsonData.MINLEN_RANGE);
document.getElementById('Minlen_text').value = jsonData.MINLEN_RANGE;
document.getElementById('Minlen_text').disabled = false;
console.log('jsonData.EXPIRY is ' + jsonData.EXPIRY);
document.getElementById('Expiry_text').value = jsonData.EXPIRY;
document.getElementById('Expiry_text').disabled = false;
document.getElementById('reset').disabled = false;
}
function initialPageLoad() {
console.log('Retrieving data from Server calling get');
serverData('get');
}
In the above script I am able to use jsonData in responseHandler() function but cannot use in``custom()` function.
I want to call my ajax function after 10 sec and my page is load on every sec.
can i store ajax function refresh rate so that after this my function load ?
any solution ? please help me.
below are my code which i am using.
my ajax function
function realtime_content()
{
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
{
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp)
{
RTupdate_query = "RTajax=1&DB=" + DB + "" + groupQS + usergroupQS + "&adastats=" + adastats + "&SIPmonitorLINK=" + SIPmonitorLINK + "&IAXmonitorLINK=" + IAXmonitorLINK + "&usergroup=" + usergroup + "";
xmlhttp.open('POST', 'demophp');
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
xmlhttp.send(RTupdate_query);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("realtime_content").innerHTML = xmlhttp.responseText;
}
}
delete xmlhttp;
}
}
This is my page load function
function refresh_display()
{
if ($start_count < 1)
{
realtime_content();
}
$start_count++;
if (ar_seconds > 0)
{
document.getElementById("refresh_countdown").innerHTML = "" + ar_seconds + "";
ar_seconds = (ar_seconds - 1);
setTimeout("refresh_display()",1000);
}
else
{
document.getElementById("refresh_countdown").innerHTML = "0"
realtime_content();
setTimeout("refresh_display()",1000);
}
}
IN ajax
setInterval(function(){yourfunction();}, 10000);
Use timeout, something like this
success: function (result) {
returned_value=result;
},
timeout: 10000,
async: false
here is the code : -
function refresh_display()
{
var count = localStorage.getItem("count");
count = count+1;
if(count=<10){
count = 0;
}
localStorage.setItem("count", count);
if ($start_count < 1)
{
realtime_content();
}
$start_count++;
if (ar_seconds > 0)
{
document.getElementById("refresh_countdown").innerHTML = "" + ar_seconds + "";
ar_seconds = (ar_seconds - 1);
setTimeout("refresh_display()",1000);
}
else
{
document.getElementById("refresh_countdown").innerHTML = "0"
realtime_content();
setTimeout("refresh_display()",1000);
}
}
and in your other function :-
function realtime_content()
{
var count = localStorage.getItem("count");
if(count<10){
return false;
}
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
{
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp)
{
RTupdate_query = "RTajax=1&DB=" + DB + "" + groupQS + usergroupQS + "&adastats=" + adastats + "&SIPmonitorLINK=" + SIPmonitorLINK + "&IAXmonitorLINK=" + IAXmonitorLINK + "&usergroup=" + usergroup + "";
xmlhttp.open('POST', 'demophp');
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
xmlhttp.send(RTupdate_query);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("realtime_content").innerHTML = xmlhttp.responseText;
}
}
delete xmlhttp;
}
}
This code has landed on my lap, and I don't have any clue what might be going on. The code is a Java Script in an ascx file as part of a chat system. The problem is that the chat content are lost after about 10 minutes. I don't know if this has anything to do with caching or not. I would like to know what might be causing the loss of chat content in this code.
<script type="text/javascript">
var roomid = '<%= ChatRoomID %>';
var status = "";
var msgTimer = "";
function StartTimers(sec) {
msgTimer = window.setInterval("DoRefresh()", sec);
}
function StopTimers() {
window.clearInterval(msgTimer);
msgTimer = "";
}
function SendMsg() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var obj = document.getElementById("txtMsg");
if (obj != null && obj.value.trim().length > 0) {
StopTimers();
status = "completed";
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=sendmsg&rid=" + roomid + "&gid=&msg=" + encodeURIComponent(obj.value) + "&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, false);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
//xmlrequest.onreadystatechange = SendMsg_Callback; //(GetBrowserVer() != "Firefox") ? (SendMsg_Callback) : (SendMsg_Callback());
obj.value = "";
CharacterCount(obj);
obj.focus();
StartTimers(60);
}
}
}
function SendMsg_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status == 0)) {
// sometimes, the completed status will equal zero in Firefox
}
}
function DoRefresh() {
StopTimers();
Refresh();
}
function Refresh() {
if (!xmlrequest)
InitObject();
if (xmlrequest) {
var nowTime = new Date().getTime(); //Get now time as random
var params = "act=refresh&rid=" + roomid + "&gid=&st=" + status;
//xmlrequest.abort();
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
xmlrequest.open("POST", "/site/function/chat.ashx?t=" + nowTime, true);
xmlrequest.setRequestHeader("If-Modified-Since", "0"); // Avoid the cache in IE
xmlrequest.setRequestHeader("Cache-Control", "no-cache");
xmlrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlrequest.setRequestHeader("Content-length", params.length);
//xmlrequest.setRequestHeader("Connection", "close");
xmlrequest.send(params);
xmlrequest.onreadystatechange = Refresh_Callback; //(GetBrowserVer() != "Firefox") ? (Refresh_Callback) : (Refresh_Callback());
}
}
function Refresh_Callback() {
if (xmlrequest.readyState == 4 && (xmlrequest.status == 200 || xmlrequest.status==0)) {
//if (xmlrequest.readyState == 4 && xmlrequest.status == 200) {
// Is ready
var response = xmlrequest.responseText;
//alert(response);
//document.write("<p>" + response + "</p>");
if (response != undefined && response.length > 0) {
var vals = null;
vals = response.split("<<<<<>>>>>");
if (vals == null || vals.length < 2) {
document.getElementById("msglist").value = response;
return;
}
/// The part one of response value is user list
var obj = document.getElementById("userlist");
if (obj != null && vals[0].length > 0) {
//alert(vals[0]);
obj.options.length = 0;
var options = vals[0].split(",");
for (i = 0; i < options.length; i++) {
obj.options.add(new Option(options[i], options[i]));
}
}
/// The part two of response value is chat message list
obj = document.getElementById("msglist");
if (obj != null && vals[1].length > 0) {
obj.innerHTML += vals[1] + "<br/>";
//obj.scrollIntoView("true");
obj.scrollTop = obj.scrollHeight;
}
/// The part three of response value is command or status
if (vals.length > 2) {
if (vals[2].toLowerCase() == "reload") {
//var sUrl = window.location.href;
//sUrl += (sUrl.indexOf("?") > 0) ? "&" : "?" + "r=t";
//window.location.href = sUrl; // window.location.href;
redirectURL(window.location.href);
}
else {
obj = document.getElementById("divStatus");
if (obj != null) {
obj.innerHTML = vals[2];
}
}
}
}
StartTimers(2500);
}
}
//////////////////////// End Call Ajax Function //////////////////////////////
function GetBrowserVer() {
var OsObject = "";
if (navigator.userAgent.toLowerCase().indexOf("msie") > 0) {
return "MSIE"; //IE
}
if (isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > 0) {
return "Firefox"; //Firefox
}
if (isSafari = navigator.userAgent.toLowerCase().indexOf("safari") > 0) {
return "Safari"; //Safan
}
if (isCamino = navigator.userAgent.toLowerCase().indexOf("camino") > 0) {
return "Camino"; //Camino
}
if (isMozilla = navigator.userAgent.toLowerCase().indexOf("gecko") > 0) {
return "Gecko"; //Gecko
}
}
function getKeycode(evt) {
// Usually evt is indicated as keypress or other key events
var keycode = 0;
if (evt != undefined && evt != null && "which" in evt) {// NN4 & FF & Opera
keycode = evt.which;
}
else if (evt != undefined && evt != null && "keyCode" in evt) {// Safari & IE4+
keycode = evt.keyCode;
}
else if ("keyCode" in window.event) {// IE4+
keycode = window.event.keyCode;
}
else if ("which" in window.event) {
keycode = evt.which;
}
return keycode;
}
function DoSendMsg(e) {
//debugger
if (e.ctrlKey && getKeycode(e) == 13) {
SendMsg();
}
}
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function redirectURL(url) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
} else {
window.location.href = url;
}
}
var CurrentUrl = '<%= Request.Url.ToString().ToLower() %>';
window.onload = function() {
if (CurrentUrl.indexOf("config_page_edit.aspx") < 0 && CurrentUrl.indexOf("config_page_preview.aspx") < 0) {
StartTimers(500);
}
}
I have a big table and my idea to optimize my program is to get the information one by one and update the table as the information arrives.
To do that I am using an ajax call to a php file which collect the data from the database. I am trying to send and receive the data one by one:
for (var i = depF; i <= depT; i++) {
xmlhttp.open("GET", "../../php_includes/reports/InventoryReportPage.php?date=" + arguments[0] + "&depF=" + i + "&depT=" + i + "&subT=" + subT + "&subF=" + subF + "&catT=" + catT
+ "&catF=" + catF + "&Tar=" + Tar, true);
xmlhttp.send();
console.log("sent ajax");
}
this code will correctly send 2 ajax calls (in the browser I can see two "sent ajax"). However in the receiver:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
console.log("recieved");
if (xmlhttp.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += xmlhttp.responseText;
}
}
}
I only see one return value. Any idea if I am even allowed to use ajax calls like this?
The whole function:
var isClicked = false;
function onClick(date, depF, depT, subF, subT, catT, catF, Tar) {
//alert(date+ depF+ depT+ subF+ subT+ catT+ catF+ Tar)
// return null;
if (!isClicked) {
console.log("in the function");
var clicked = arguments[0];
isClicked = true;
var div = clicked + "apDiv";
var browserSupport = (navigator.userAgent.indexOf('Firefox') != -1) || ((navigator.userAgent.indexOf('Chrome') != -1) || (navigator.userAgent.indexOf('Safari') != -1));
if (browserSupport) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (!xmlhttp) {
alert("your browser doens't supposrt XMLHTTP " + navigator.userAgent);
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
console.log("recieved: "+xmlhttp.responseText);
if (xmlhttp.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += xmlhttp.responseText;
}
}
}
for (var i = depF; i <= depT; i++) {
xmlhttp.open("GET", "../../php_includes/reports/InventoryReportPage.php?date=" + arguments[0] + "&depF=" + arguments[1] + "&depT=" + arguments[2] + "&subT=" + subT + "&subF=" + subF + "&catT=" + catT
+ "&catF=" + catF + "&Tar=" + Tar, true);
xmlhttp.send();
console.log("sent the ajax");
}
}
}
The reason your code don't work as you expect is that you basically overwrite the requests you are doing. You can try something like this:
var reqs = [];
for (var i = depF; i <= depT; i++) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/", true);
xmlhttp.send();
reqs.push(xmlhttp);
}
reqs.forEach(function(req) {
req.onreadystatechange = function()
{
if (req.readyState === 4 && req.status === 200)
{
console.log("recieved");
if (req.responseText) {
var table = document.getElementById("inventoryReport");
table.innerHTML += req.responseText;
}
}
}
})