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;
}
}
}
})
Related
I’ve got a call that brings up an url id for a recipe, that I’m trying feed into another call to return additional recipe data, but I think the scope is incorrect somewhere.
I’m getting
Cannot read property 'id' of undefined at XMLHttpRequest.http.onreadystatechange
in Chrome.
function searchFood() {
var http = new XMLHttpRequest();
var foodID = 'a1e1c125';
var foodApiKey = 'c84a720e4f1750b59ce036329fccdc00';
var foodMethod = 'GET';
var url = 'http://api.yummly.com/v1/api/recipes?_app_id=' + foodID + '&_app_key=' + foodApiKey + '&q=scandinavian';
http.open(foodMethod, url);
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE && http.status === 200) {
var foodData = JSON.parse(http.responseText);
var foodName = foodData.matches[0].recipeName;
console.log(foodData);
for (var i = 0; foodData.matches.length; i++) {
var recipeId = foodData.matches[i].id;
console.log(recipeId);
}
function getRecipe() {
var http = new XMLHttpRequest();
var foodID = 'a1e1c125';
var foodApiKey = 'c84a720e4f1750b59ce036329fccdc00';
var foodMethod = 'GET';
var url = 'http://api.yummly.com/v1/api/recipe/' + recipeId + '?_app_id=' + foodID + '&_app_key=' + foodApiKey;
http.open(foodMethod, url);
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE && http.status === 200) {
var data = JSON.parse(http.responseText);
console.log(data);
} else if (http.readyState === XMLHttpRequest.DONE) {
alert("something went wrong");
}
};
http.send();
};
} else if (http.readyState === XMLHttpRequest.DONE) {
alert('Something went wrong')
}
};
http.send();
};
Any tips would be appreciated, thanks
Your truthy check is always true
for (var i = 0; foodData.matches.length; i++)
you are missing i<
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
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;
}
}
I am using JavaScript.
I amusing a setInterval timer method.
Inside that method I am changing the values of module variables.
The thing is in IE the changes to the variables are not 'saved'. But in Chrome they are.
What is the accepted practice to do what I need to do?
this is my code:
function start()
{
var myVar = setInterval(function () { GetTimings() }, 100);
}
var currentts1;
var currentts2;
var currentts3;
var currentts4;
var frameCounter;
function GetTimings() {
if (frameCounter < 1) {
frameCounter++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var nextts = xmlhttp.responseText;
var bits = nextts.split('|');
if (currentts1 != bits[0]) {
currentts1 = bits[0];
postMessage("0|" + bits[0]);
}
if (currentts2 != bits[1]) {
currentts2 = bits[1];
postMessage("1|" + bits[1]);
}
if (currentts3 != bits[2]) {
currentts3 = bits[2];
postMessage("2|" + bits[2]);
}
if (currentts4 != bits[3]) {
currentts4 = bits[3];
postMessage("3|" + bits[3]);
}
frameCounter--;
}
}
xmlhttp.send();
}
}
The variables:
currentts1
currentts2
currentts3
currentts4
frameCounter
values are not preserved...
Try this, but notice I changed the currentts* to an Array when you try to view them
function start() {
var myVar = setInterval(GetTimings, 100);
}
var currentts = [null, null, null, null];
var in_progress = 0; // clear name
function GetTimings() {
var xhr;
if (in_progress > 0) return; // die
++in_progress;
xhr = new XMLHttpRequest();
xhr.open('GET', urlTS);
function ready() {
var nextts = this.responseText,
bits = nextts.split('|'),
i;
for (i = 0; i < currentts.length; ++i)
if (currentts[i] !== bits[i])
currentts[i] = bits[i], postMessage(i + '|' + bits[i]);
--in_progress;
}
if ('onload' in xhr) // modern browser
xhr.addEventListener('load', ready);
else // ancient browser
xhr.onreadystatechange = function () {
if (this.readyState === 4 && xhr.status === 200)
ready.call(this);
};
// listen for error, too?
// begin request
xhr.send();
}
What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.