JavaScript Ajax save result - javascript

I'm having a problem. I'm trying do ajax on my own, but I have problem with saving result from ajax call. I want it to do just like jQuery does, or similarly.
So, I have a function called ajax, with I parameter, and this parameter is an object with properties like: method, url, async, data, and success ...
When I call ajax function, I have no problem except success .. I want it just like jQuery (dont ask me why I dont want to use jQ). So I want this
ajax({
method: "POST",
url: "ajax.php",
async: false,
data: "name=something",
success: function(result) {
console.log(result);
}
});
and I have a problem to save result to parameter in definition of ajax function, and here just use it.
Here's ajax.php
<?php
$name = "The input is: " . $_POST['name'];
return $name;
?>
Here's a definition of an ajax function:
var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
/* ////////////////////////////////////////////
HERE I HAVE PROBLEM
/////////////////////////////////////////////*/
// this is obviously wrong (I know it is)
arg.success = function (something) {
something = xmlhttp.responseText;
}
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};
How to save a xmlhttp.responseText to arg.success function parameter in a way that I can use the parameter in ajax function calls? Should I use callbacks?
EDIT: Thanks, it works but, it only print "The input is: ". How can I fix it?

You want to call the method, not set it.
arg.success(xmlhttp.responseText);

var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
arg.success(xmlhttp.responseText);
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};

If you got status 200 and there is some data that is from server.
With callback: If need someting to return you can use callback.
var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var Success = function (xmlhttp.responseText);
alert(Success);
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};
function Success(e)
{
alert(e);
retrun e;
}
WithOut Callback: you dont need to return any data
var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};

Related

Javascript statement evaluation error

I have a JSP on that I have written a javascript, condition is there are four records with same product id but each having a different record id. When i am trying to update the 4th record quantity on the onchange() event but still its taking first record id. Below i am mentioning the statement in which its taking the record id
<script type="text/javascript">
$(function () {
// alert(1);
$("#SaveBtn").click(function () {
// alert(2);
$("#ConfirmLinePageFRM").submit();
// alert(3);
});
$("#UPC_EAN").change(function () {
// alert(4);
// $("#Status").html("UPC/EAN Code in Processing Plz wait");
val = $(this).val();
var flag = 0;
if ($("UPC_EAN").val() == 'OK') {
// alert(5);
$("#ConfirmLinePageFRM").submit();
}
//loadXMLDoc();
//alert ("Product Find") ;
$(".Abc").each(function () {
// alert(6);
// alert($(this).attr("axp"));
if (($(this).attr("axp") == val) && (flag != 1)) {
// alert(7);
var confirmQty = $("#ConfirmQry" + $(this).val()).val();
var targetQty = $("#TargetQty" + $(this).val()).val();
var id = $(this).val();
if (parseInt(confirmQty) >= parseInt(targetQty)) {
// alert(8);
flag = 2;
} else {
// alert(9);
$("#UPC_EAN").val("");
$('#UPC_EAN').focus();
flag = 1;
var id = $("#id").val();
var c_id = $(this).val();
// alert("before loadXMLDoc");
loadXMLDoc(id, c_id);
//$("#ConfirmQry" + $(this).val()).val(parseInt($("#ConfirmQry" + $(this).val()).val()) + 1);
// alert("after loadXMLDoc");
// alert("0 :" + scanOK);
}
}
});
$("#Status").html("");
if (flag == 0) {
// alert(12);
$("#display-error").html("Wrong Barcode Plz Ch Again.");
$("#display-error1").html("");
$("#UPC_EAN").val("");
$("#UPC_EAN").focus();
} else {
// alert(13);
if (flag == 2) {
// alert(14);
$("#display-error").html("All confirm qty already done");
$("#display-error1").html("");
$("#UPC_EAN").val("");
$("#UPC_EAN").focus();
} else {
// alert(15);
$("#display-error").html("");
}
}
// alert("before showhide");
showhide();
// alert("after showhide");
});
});
function loadXMLDoc(id, c_id)
{
// alert(18);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
// alert("xmlhttp.readyState :" + xmlhttp.readyState);
// alert("xmlhttp.status :" + xmlhttp.status);
// alert("xmlhttp.responseText :" + xmlhttp.responseText);
// // below is for direct testing
// if (xmlhttp.readyState == 4 && xmlhttp.status == 0 && xmlhttp.responseText == "") {
// // below is for netbeans ide testing
// if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText == "") {
if (xmlhttp.readyState == 4 && xmlhttp.status == 0 && xmlhttp.responseText == "") {
alert("Network Connection Error");
$("#ConfirmLinePageFRM").submit();
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var textRespose = xmlhttp.responseText;
if ($.trim(textRespose) == 'U') {
$("#display-error1").html(val + " - Updated Sucessfully");
$(".bgColor").css("background-color", "#aad4ff");
$(":input").css("background-color", "#aad4ff");
$("#UPC_EAN").css("background-color", "#ffffff");
$("#ConfirmQry" + c_id).removeAttr("readonly");
$("#ConfirmQry" + c_id).val(parseInt($("#ConfirmQry" + c_id).val()));
$("#UpcCode" + c_id).css("background-color", "#ffffff");
$("#Location" + c_id).css("background-color", "#ffffff");
$("#tQty" + c_id).css("background-color", "#ffffff");
$("#cQty" + c_id).css("background-color", "#ffffff");
$("#ConfirmQry" + c_id).css("background-color", "#ffffff");
$("#TargetQty" + c_id).css("background-color", "#ffffff");
showhide();
}
if (xmlhttp.responseText == "" || xmlhttp.responseText == "Database conectivity issue") {
// alert("Network Connection Error");
// $("#ConfirmLinePageFRM").submit();
}
}
//
}
xmlhttp.open("GET", "AjaxLogicForManually?id=" + id + "&c_id=" + c_id, true);
xmlhttp.send();
}
function manuallyEnterValue() {
// alert(26);
var qtyFlag = 0;
// alert(261);
$(".Abc").each(function () {
// alert(262);
// alert(val);
// alert($(this).attr("axp"));
var scanVal = $("#Line").val();
//var scanVal = document.getElementById("LineNo");
// var scanVal = $("input").attr("axp").val;
// alert($('input').attr('axp'));
// alert(scanVal);
if (($(this).attr("axp") == val) && (qtyFlag != 1)) {
// alert(263);
var confirmQty = $("#ConfirmQry" + $(this).val()).val();
var targetQty = $("#TargetQty" + $(this).val()).val();
alert(confirmQty);
alert(targetQty);
if (parseInt(confirmQty) > parseInt(targetQty)) {
// alert(28);
qtyFlag = 2;
}else{
// alert(29);
//var qtyVal = $("#ConfirmQry" + c_id).val;
qtyFlag = 1;
var id = $("#id").val();
//var c_id = $(".Abc").val();
var c_id = $(this).val();
// alert(confirmQty);
// alert(id);
// alert(c_id);
// alert("before loadXMLDoc");
loadXMLDocForManuallyEnter(confirmQty, id, c_id);
// alert("after loadXMLDoc");
}
}
});
if (qtyFlag == 0) {
// alert(24);
$("#display-error").html("Wrong Barcode Plz Ch Again.");
$("#display-error1").html("");
$("#UPC_EAN").val("");
$("#UPC_EAN").focus();
} else {
// alert(13);
if (qtyFlag == 2) {
// alert(14);
$("#display-error").html("Product Con.Qty Exceed to the Tar.Qty");
$("#display-error1").html("");
$("#UPC_EAN").val("");
$("#UPC_EAN").focus();
} else {
// alert(15);
$("#display-error").html("");
}
}
showhide();
}
function loadXMLDocForManuallyEnter(qtyVal, id, c_id){
// alert(228);
// alert(qtyVal);
// alert(id);
// alert(c_id);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
// alert("xmlhttp.readyState :" + xmlhttp.readyState);
// alert("xmlhttp.status :" + xmlhttp.status);
// alert("xmlhttp.responseText :" + xmlhttp.responseText);
// // below is for direct testing
// if (xmlhttp.readyState == 4 && xmlhttp.status == 0 && xmlhttp.responseText == "") {
// testing
// if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText == "") {
if (xmlhttp.readyState == 4 && xmlhttp.status == 0 && xmlhttp.responseText == "") {
alert("Network Connection Error");
$("#ConfirmLinePageFRM").submit();
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// alert(119);
var textRespose = xmlhttp.responseText;
if ($.trim(textRespose) == 'U') {
$("#display-error1").html(val + " - Updated Sucessfully");
$(".bgColor").css("background-color", "#aad4ff");
$(":input").css("background-color", "#aad4ff");
$("#UPC_EAN").css("background-color", "#ffffff");
$("#ConfirmQry" + c_id).prop('readonly', true);
$("#ConfirmQry" + c_id).val(parseInt($("#ConfirmQry" + c_id).val()));
$("#UpcCode" + c_id).css("background-color", "#ffffff");
$("#Location" + c_id).css("background-color", "#ffffff");
$("#tQty" + c_id).css("background-color", "#ffffff");
$("#cQty" + c_id).css("background-color", "#ffffff");
$("#ConfirmQry" + c_id).css("background-color", "#ffffff");
$("#TargetQty" + c_id).css("background-color", "#ffffff");
showhide();
}
if (xmlhttp.responseText == "" || xmlhttp.responseText == "Database conectivity issue") {
alert("Network Connection Error");
// $("#ConfirmLinePageFRM").submit();
}
}
//
}
xmlhttp.open("GET", "AjaxLogicForManuallyEnterValue?id=" + id + "&c_id=" + c_id + "&qtyVal=" + qtyVal, true);
xmlhttp.send();
}
</script>
its taking the record id of first record. How can I take the id of 4th record and it is happening when product id is same for all four record.
Please help me

how to call ajax after 10 sec and my page is load on every sec

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;
}
}

How to convert jquery ajax to native javascript?

here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}
I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}

Data gets lost in a java script and .Net based chat app

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);
}
}

send multiple ajax call to a same file

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;
}
}
}
})

Categories