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);
});
Related
I am using AJAX to display upcoming events on a website. To that end, I call a JavaScript function via onload="showEvents(3);", see the function below:
function showEvents (amount) {
// are there Events?
if (document.getElementById("eventsDiv")) {
document.getElementsByClassName("info")[0].innerHTML = 'Loading events...';
// initialize XML Http Request
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("eventsDiv").innerHTML = xmlhttp.responseText;
}
}
// send request
xmlhttp.open("GET", "./events.php?number=" + encodeURIComponent(amount), true);
xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send();
}
}
The file events.php is a PHP file in the same directory, and it connects to the database to fetch the upcoming events. The HTML header of the main website includes
<base href="http://www.my-domain.com/">
The problem: I get a "Cross Orign" error message (in Firefox), preventing my parent index.html file accessing the events.php. As I understand, this error message should not appear since I am using a resource from the same directory.
Ok that's ok, you also can do like this...
if($_SERVER['HTTP_ORIGIN'] == "http://your-domain.com") {
header('Access-Control-Allow-Origin: http://your-domain.com');
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>
How can I detect whether an Ajax request failed to load a file.
Here is my code for reference:
var pro = undefined;
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
pro = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","data.json",true);
xmlhttp.send();
Please, no jQuery.
Thanks!
you can check if the http status is 500 or more than 500 which means an error occurred in the request http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error
if (xmlhttp.status >= 500){
alert('error');
}
NOTE: you can also consider other http status numbers as you like
onerror callback should be used for handling error, like this:
xmlhttp.onerror = function onError(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
As far as I know, jQuery library also uses this method. Not sure which all browsers support this, but this surely works in firefox.
What I do is use a global variable I name 'boomerang' (witty I know)
so when you send the request out make boomerang=1 and then on its success make boomerang=0
then at some appropriate time after you send the request out then you can just check if boomerang =1 or =0
you need to check the status code- 4xx and 5xx codes are errors.
here's a list of codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
You won't need much more. Do something in the else clause other than the comment.
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
pro = JSON.parse(xmlhttp.responseText);
} else {
if (xmlhttp.readyState==4) {
// Something failed
}
}
}
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
I'm fairly new to the world of web development and am trying to read a txt file in internet explorer 8 and compare it to source code of a website to see if they are equal. This is so I can work out if the web page is functioning correctly.
I managed to get the source code with an xmlhttprequest and have tried the same to get the text file (which is in the same domain as my web page) and I am getting an access denied error.
After some research I can see that cross-domain xmlhttprequests won't work but that's not what I'm trying to do so I'm not sure how to proceed.
Having run the same code in Firefox(current version). It will read the file but not the web page!
I don't mind which of the two browsers I end up using but at the moment each does half of what I want it to.
my code is:
function source1(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "http://website",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById('textzone').value = xmlhttp.responseText
var inputString = xmlhttp.responseText;
alert(inputString);
comparison(inputString)
}
}
xmlhttp.send(null)
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp.send(null)
}
All I need to know is why either the file won't open in ie8, or why the website source code shows up blank (in the alert) in firefox. Any help would be appreciated.
It could be a browser support issue.
Try the following code to initialize your XMLHttpRequest :
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
Check your comparison function. You should you xmlhttp1 instead of xmlhttp at 2 places
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
<!--alert(xmlhttp1.responseText)-->
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp1.send(null)
}
Try to add the if(xmlhttp.status == 200) { } stuff. Remember both of these are looping through status' "AND" readystates.
Technically you could be erroring somewhere (I'd rather not speculate on) halting progress to next request or whatever without the status check.
Also you "should" try other request techniques. ie.. xmlhttp.onreadystatechange = function(){itsReady(inputString)}; // we keep this line short and simple calling to another func that contains your status and readystate checks, response stuff, and more func.
On a pretty normal run the Loop looks like:
hi rdySte:1///status 0////////
hi rdySte:2///status 200////////
hi rdySte:3///status 200////////
hi rdySte:4///status 200////////
I ran into a lot of weird issues trying the long onreadystatechange = function (){ ... All stuff..} I successfully run a crazy set of request functionalities using the short onreadystatechange technique.
I noticed at the last minute->
is there a reason why the async flags are different between your funcs? I'd set them all to true unless you have a great reason.
This will work: (to test: 2 pages t1.php contains a num or whatever and t2.txt that has a num in sam dir as the funcs are called in)
function source1(){
var avar = 1;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "t1.php",true); // shortened f-names for ease of test
xmlhttp.onreadystatechange = function(){jsg_snd(avar)};
xmlhttp.send(null)
}
function jsg_snd(avar){
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
var inputString = xmlhttp.responseText;
document.getElementById('text_zone').innerHTML = inputString;
document.getElementById('text_zone1').value = inputString;
// alert(inputString);//
comparison(inputString)
}
}
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "t2.txt", true);
xmlhttp1.onreadystatechange= function(){jsg_snd1(inputString);};
xmlhttp1.send(null)
}
function jsg_snd1(inputString){
if (xmlhttp1.readyState==4) {
if (xmlhttp1.status == 200) {
var compareString = xmlhttp1.responseText;
//alert(compareString)
if(inputString==compareString){
//alert("Strings are equal");
document.getElementById('text_zone').innerHTML += "; Ok "+inputString+"=="+compareString+"";
}
}
}
}
Now the html in your body should look like:
<tt id = 'text_go' onMouseUp="source1();" >Go!</tt>
<tt id = 'text_zone' onMouseUp="text_zone.innerHTML = '';" >Click to clear!</tt>
<input type ='text' id = 'text_zone1' onMouseUp="text_zone1.value = '';" value = 'Click to clear!' >
The extra stuf is for ___s & giggles.