else clause to repeat ajax triggers too many times - javascript

I have an ajax function on my website which calls a cgi script. infrequently, this script returns a 500 error. I am trying to change the AJAX call so that when this happens, it will repeat the request. I have tried to do that as follows:
function shelverx() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
I'm wondering if there is a better way to accomplish this? I find that what happens is that whenever there is a 500 error, the shelverx function is called four times, even if the second call is successful. Is there a way to repeat the call only once per error?
I also tried to accomplish the same thing by changing the entire ajax call to jQuery and using the following error function:
error: function(xhr, textStatus, errorThrown ) {
this.tryCount++;
if (this.tryCount<=this.retryLimit) {
$.ajax(this);
return;
}
But I got an Unexpected Token : error. If anyone could help me to get either of these methods to work I would appreciate it greatly. My goal is to have the ajax call repeat only once per 500 error.

Jonathan -
The code snippet below works as you want. The counter holds its value between calls and stops requests at 5. I also changed the IF statement logic and added a timer to wait 1 second between tries. Give it a try.
Note that the original logic doesn't work correctly. In the debugger it was incrementing the counter multiple times per each request. Much better to check status after readyState = 4.
Original Code:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
Tested and working example:
<!doctype html>
<html>
<body>
<script type="text/javascript">
var postdata = '';
var filepath = 'NothingHere.html';
var limit = 0;
function shelverx() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.info('Success: Recieved ' + xmlhttp.responseText.length + ' bytes');
}
else {
limit++;
console.info( 'Error: ' + xmlhttp.status + ':' + xmlhttp.statusText );
if (limit < 5) setTimeout( shelverx, 1000 );
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
shelverx();
</script>
</body>
</html>

Related

Getting duplicate prints

I am facing some unidentified issue. please any one help me to sort out.
problem is when runonload() function runs, we will get print but I am getting duplicate prints (with same data). but this function executes one time (logs in this function write one time) but fnQrCode() & fnBuildBody() calling twice (logs in these function writes twice and getting prints twice). there is no loop for second time. Below is my code snippet.
var xmlcodebar="";
---
---
function runonload(){
code for print preparation
-------
-------
fnQrCode(dealref,sterlingQR, deliveryType); //this function for qr code generation
xmlcodebar = "data:image/png;base64,"+xmlcodebar;
footer11 = '<td width="100%"><img src='+xmlcodebar+' align="center" width="750" height="150"></td>';
footer12 = '</tr></table>';
fnBuildBody(strRows,strPrintData, Number(strPageLength),footer1,footer2, footer3, footer4, footer5, footer6, footer7, footer8,footer9, footer10, footer11, footer12); //this function for printing
-------
--------
}
function fnQrCode(dealref,sterlingQR,deliType){
var data =sterlingQR+";"+dealref+"$;"+deliType;
var strQueryString = "hdnOptPage=QRCODE&DATA="+data;
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Browser doesn't supports Http Request");
return;
}
var url = "<%=CONTROLSERV_TFROUT%>"+"?"+strQueryString;
xmlHttp.onreadystatechange = stateBarcode;
xmlHttp.open("POST",url,false);
xmlHttp.send();
}
function stateBarcode() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if(xmlHttp.status == 404 || xmlHttp.status == 500){
alert("Problem occured at server. Please try again.");
window.event.returnValue=false;
return;
} else if (xmlHttp.status == 200) {
xmlcodebar = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject() {
var objXMLHttp = null;
//check whether browser supports HttpRequest
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return objXMLHttp;
}

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

Var not found in IF statement, but is set correctly.

I have a var that's value is set, with an if statement to check which value, then deploy depending on the statement.
function Sort() {
var Response = document.getElementById("ResponseDiv").innerHTML;
if (Response == "Verified.") {
alert("Verified");
}
else if (document.getElementById("ResponseDiv").innerText == "Not verified.") {
alert("Not verified");
}
else {
alert("Else: " + Response);
}
}
My code isn't landing on "Verified" or "Not Verified" instead it lands on the else statement. I went through several times thinking I had a typo but isn't the same.
The ResponseDiv is filled by this (which works fine):
function Check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + Http + '/ID_' + ID + '.html', false);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("ResponseDiv").innerHTML = xhr.responseText;
//setTimeout(Sort, 200);
Sort();
}
}
};
xhr.send(null);
}
My div gets the correct data, and the alert box in the else even gives me what I'm looking for, but lands on the else.
Debugger shows Response as coming back as "Verified.\n", but in no other way. However statement works fine when coded as if(Response == "Verified.\n").

HTTP(S) Request With Javascript and receive JSON data

since I'm new on http(s) request case, I have one case here that must be written on Javascript, hope someone could help me because I've searched everywhere and couldn't find the answer. Here is the case:
However, when the connection rate goes up to 5, I will have to wait until one of them is finished corresponding before sending a request, so that 2 or more of them are not over 5.
In addition, when the response code is not 200, I will retry 3 times. If the response code is still not 200 after retrying 3 times, the error function will pursue. I also must receive the Json data of the response body as an argument function.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else if (xmlhttp.readyState==4 && xmlhttp.status!=200){
document.write("Error");
}
}
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
Please help on comment below or you can suggest me links that could help me with this case. Thanks.
Something like this?
Concerning the connection rate, you can go multiple directions with this, since it isn't 100% clear what you want. The easiest solution would be to have your asp page return a 'fake error' as a json object and have the success function check if the response contains this 'fake error'. If so, resend the request to the server. Or you could have the asp page only send a response, if the connection rate < 5, but that might mean your user ends up waiting longer that expected.
var getJSON = function getJSON( resource, success, failure ) {
var xmlhttp = (window.XMLHttpRequest) ? xmlhttp=new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
retry = 0;
success(xmlhttp.responseText, 200);
}
else failure(xmlhttp.status);
}
xmlhttp.open("GET", resource, true);
xmlhttp.send();
},
retry = 0,
success = function success( response, status ) {
document.querySelector("#myDiv").textContent = response;
},
failure = function failure( status ) {
if (retry < 3) {
retry += 1;
getJSON("demo_get.asp", success, failure);
}
else console.log('ERROR');
};
document.querySelector('button').addEventListener('click', function( event ) {
getJSON("demo_get.asp", success, failure);
});

Ajax call not successful

I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean

Categories

Resources