onreadystatechange is too slow - javascript

Do anyone know what I'm doing wrong or why AJAX callbacks are TOO slow? Here's code:
function new_xmlhttp() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function ajax_get(data, args) {
xmlhttp = new_xmlhttp();
xmlhttp.open("GET", "functions.php?" + data, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// OK.
alert(args);
}
}
xmlhttp.send(null);
}
Sometimes it takes 2-3 seconds to load (data is max 10 bytes long.)
Tested on Firefox and Chrome under Linux.

Related

Ajax function in javascript is not working in mozilla firefox browser, why?

Follownig is my javascript code, ajax function is used to read response from
server. but xmlhttp.status is always 0 in firefox browser, why? please help me.
function ajaxAsyncRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveObject("Microsoft.XMLHTTP");
}
//creating asynchrounous GET request
var tempValUrl = $(".urlVal").val();
var urls = tempValUrl + '/Department/departmentAdminTokenReceive';
xmlhttp.open("GET", urls, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert("readyState"+xmlhttp.readyState);
alert("status"+xmlhttp.status);
if (xmlhttp.status == 200) {
var data = xmlhttp.responseText;
//for signing
var signarr = data.split("$$");
//for signing
document.getElementById('signName').value = signarr[1];
document.getElementById('signCertName').value = signarr[2];
document.getElementById('signCa').value = signarr[3];
document.getElementById('signExpiryDate').value = signarr[4];
document.getElementById('signPublicKey').value = signarr[5];
}
}
}
}

set time out in ajax call while using core javascript

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.
here is my code:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)
If you want to simply add timeout, You can add it in the first function in three places:
setTimeout(function() {callback(this.responseText, params)}, 1000)
And your callback will execute around 1s later. The second palce is second call of callback.
Third place that i would suggest is to wrap this function like above:
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:
Here is your code with first approach:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
console.log(new Date());
setTimeout(function() {callback(this.responseText, params)}, 2000);
} else {
console.error((new Date()).getSeconds());
setTimeout(function() {callback(this.responseText)}, 2000);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Maybe the answer to this question will help.
Timeout XMLHttpRequest
since from what i understand you need to set timeout for xmlhttprequest,
you can use xmlhttp.timeout = /*some number*/

JS file works fine on IE but not on other browsers

The function below gets results in ie but not on the other browsers. Any suggestion?
function show_packet(str, company) {
var cam = document.getElementById("company");
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("packet_1").innerHTML = xmlhttp.responseText;
document.getElementById("icon_1").innerHTML = "";
}
}
xmlhttp.open("GET", "show_packet.php?car_moto=" + encodeURIComponent(str, true) + "&cam=" + encodeURIComponent(cam.value, true));
xmlhttp.send();
}
vars and functions are hoisted to the top of their containing function. Declare your var once at the top, and only assign it in the if/else.

How to get my ajax to work in IE

My code works in Firefox, but it does not work on the IE
Here is my script:
<script type="text/javascript">
var request = new XMLHttpRequest();
function saseangol() {
request.open ("GET", "saseangol.html",true);
request.onreadystatechange = function() {
if(request.readyState == 4) {
document.getElementById('cont').innerHTML = request.responseText;
}
}
request.send(null);
}
var request = new XMLHttpRequest();
function sase() {
request.open ("GET", "sase.html",true);
request.onreadystatechange = function() {
if(request.readyState == 4) {
document.getElementById('cont').innerHTML = request.responseText;
}
}
request.send(null);
}
</script>
Can someone help me plz?
Can you please check which version of IE you are using, and does it support XMLHttpRequest. Because IE7+ has built-in XMLHttpRequest object.
xmlhttp = new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
in javascript:
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
If you want to use AJAX cross-browser you can do something like this...
function createXHR() {
if (typeof XMLHttpRequest !== "undefined") {
return new XMLHttpRequest();
} else {
var versions = ["MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.3.0"];
for (var i = 0, length = versions.length; i < length; i++) {
try {
var xhr = new ActiveXObject(versions[i]);
return xhr;
} catch (error) {}
}
}
alert("Your Browser Doesn't Support XmlHttp");
return null;
}
You use asynchronous request so when it should be performed, you just redeclared var request = new XMLHttpRequest(); variable and so there might be reason of your problem

problem in javascript

i have sorted xml file on the basis of item no.now i am trying to display data in javascript, but my code doesn't work, can anybody tell me what is wrong here
item.php:
$xmlFile = "items.xml";
$doc= DOMDocument::load($xmlFile);
$item = $doc->getElementsByTagName("item");
$items=array();
foreach($item as $node)
{
$itemno = $node->getElementsByTagName("itemno");
$itemno = $itemno->item(0)->nodeValue;
$quantity = $node->getElementsByTagName("quantity");
$quantity = $quantity->item(0)->nodeValue;
$available = $node->getElementsByTagName("available");
$available = $available->item(0)->nodeValue;
$items[$itemno]= array($itemno,$quantity,$available);
}
ksort($items, SORT_NUMERIC);
foreach($item AS $ite => $no)
{
$itemnum=$no[0];
$qty=$no[1];
$avail=$no[2];
echo $itemnum;
echo $qty;
echo $avail;
}
js:
var xhr = createRequest();
function getit( ) {
xhr.open("GET", 'item.php', true);
xhr.onreadystatechange = getConfirm;
xhr.send(null);
}
function getConfirm()
{
if ((xhr.readyState == 4) &&(xhr.status == 200))
{
var data = xhr.responseText;
alert(data);
}
}
try xmlrequest in this flow in your javascript:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tbRow").innerHTML=xmlhttp.responseText;
//lo();
}
}
xmlhttp.open("GET","tbrow.php",true);
xmlhttp.send();
Here "tbRow" is a "div" id. i.e.,
<div id="tbRow"></div>

Categories

Resources