request.xhr undefined in Ext JS - ajax

my web site is made using Ext JS 4.1 framework and ASP .Net MVC v3. When new frame is rendered there are 19 separate AJAX requests for retrieving data in JSON-format. All requests are familiar and made by Ext.Ajax.request(). Example:
Ext.Ajax.request({
url: getOrderLink,
method: "GET",
params: { recId: orderRecId },
headers: {
'Accept': 'application/json'
},
success: function (response) {
var order = Ext.decode(response.responseText);
...
}
});
In some cases there are errors in ext-all.js in
onStateChange : function(request) {
if (request.xhr.readyState == 4) {
this.clearTimeout(request);
this.onComplete(request);
this.cleanup(request);
}
},
where request has no property xhr so that request.xhr.readyState throws exception "Cannot read property 'readState' of undefined".
This errors appear not for all requests and don't effect site work(responses are retrieved successfully). Some times this errors don't appear at all. Timeout for all requests is set to 30s by default and they take about 1.5-2 seconds each.
I am using Google Chrome 21.
Could you please give me some idea why it's happening.

The problem seems to occur if and only if you have a breakpoint or a "debugger;" line in anything related to AJAX. For me it happened in Chrome, haven't tried other browsers yet.
In my case it happened when I had set a breakpoint in a load event handler for a store like code example below.
But the error occurrs if you set a breakpoint inside the Ext onStateChange function in the framework itself as well.
If disabling your breakpoints and debugger; calls removes the error you can safely ignore it!
There is a similar thread on ExtJS forums. Sencha might add a fix.
Ext.define('MyApp.controller.MyController', {
extend: 'Ext.app.Controller',
stores: ['Projects'],
init: function () {
this.getProjectsStore().addListener(
"load",
this.onProjectsStoreLoaded,
this
);
},
onProjectsStoreLoaded: function () {
console.log('MyController: onProjectsStoreLoaded');
debugger; // <- this causes the errors to appear in the console
SomeOtherThingsIWantedToDebug();
}
}

Related

jQuery-Mobile: ajax request stops working after changePage failure

I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>

How to run a consuming process before sending data with ajax and jquery on the background with the spinner running?

I am trying to send data to server using ajax, but the problem is that I have a consuming process before sending the data.
The process takes about 5 seconds and the spinner has to run in the process.
So in my code the spinner doesnt show until the ajax call starts (probably because the process is blocking everything)
If I move the call "consumingprocess" into "beforesend", then it doesnt work and I am not sure why.
So the question is how to show the spinner, while everything is beeing called (the consumingprocess and the ajax call)
Thanks
This is my code:
$("#btnAccept").bind("click", function(event, ui) {
//start spinner, works fine but only shows after consumingprocess has finished
$.mobile.loading( 'show' );
console.log("btnAccept");
var data = consmuingprocess();
console.log(data);
// data is fine
$.ajax({
type : "POST",
url : url,
dataType : "xml",
contentType : "text/xml;charset=UTF-8",
data : data,
requestHeaders : {
Origin : '*'
},
crossDomain : true,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxx");
console.log("beforeSend");
},
error : errorAJAX,
success : parseXml
});
});
});
What you can do is
call your loading window
delay so the loading window has a chance to display
run the rest of your code.
You would do this using an interval:
$("#btnAccept").bind("click", function(event, ui) {
var intervalId;
function delayedStuff = function() {
// make sure we only run this once
window.clearInterval(intervalId);
var data = consmuingprocess();
$.ajax({
// set up your ajax request and handlers
});
};
$.mobile.loading( 'show' );
// wait 1/2 second, then run delayedStuff
intervalId = window.setInterval(delayedStuff, 500);
});
But this technique comes with an important caveat: while your very expensive consumingProcess function is running, all animations and javascript still comes to a halt. On Chrome, even animated gifs stop running. All we've done here is just given your page changes a chance to display.
There are a couple of possible solutions available:
Take a closer look at your consumingprocess() function and see if it can be optimized. There is probably a faster way to do whatever it is you're doing that's taking so long.
Use WebWorkers. The downside is compatibility: IE and most older browsers don't support it. I haven't done multi-threaded programming with JavaScript at all, so I don't know how effective this is.

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

request.html in local file gets status = 0

I'm making a functional mockup using mootools,and in this prototype I have to load an html file via request.HTML, but as soon as I run the script, the call never reaches the onSuccess due to the state = 0.
The blame could be that the request is treated as a violation of the crossdomain.
So I was wondering if is out there a way to work it around?
this is the code I use for performing the request
req = new Request.HTML({
url: "detail.html",
onFailure: function(a) { console.log("iFailed: " + a); },
onSuccess: function(r3, rEls, rHTML, rJS) {
console.log("It worked!!");
},
onComplete: function() { console.log('completed'); }
}).send();
as I run this it always goes into the onFailure and in the onComplete without hitting the onSuccess.
I need this to work with safari, because the mock shall work on an iphone/ipad/ipod.
thx a ton
in the end I managed it bu injecting an iframe via js, instead of populating the div via ajax.
it's kind of lame and it sucks a lot, but at least it work and it's good for prototyping purposes.

ajax settimeout to refresh div

I am displaying a graph using jQplot to monitor data.
To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below).
On the server, a PHP script retrieves the data from a database.
On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000).
On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message.
Monitoring XHR learns that the browser crashes after approximately 200 requests.
As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing.
This works, but is not an ideal situation.
Any better solution to this problem is very much appreciated.
Thanks and regards, JZB
function ajax() {
$.ajax({
cache: false,
url: 'monitor.php',
data : { x: id },
method: 'GET',
dataType: 'json',
success: onDataReceived,
error: onDataError
});
function onDataReceived(series) {
$('#chartdiv_bar').html('');
$.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));
errorcount = 0;
setTimeout(ajax, 5000);
}
function onDataError(jqXHR, textStatus, errorThrown) {
errorcount++;
if (errorcount == 10) {
alert("No server response:\n\n" + textStatus + "\n" + errorThrown);
} else {
setTimeout(ajax, 5000);
}
}
}
Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.
you may want to try to clear the current timer and then start the next timer
var t; //global
In each of your call back functions:
if(t)
clearTimeout(t);
t = setTimeout(ajax, 5000);
more info on timer here: w3 school
I removed the jqplot call as suggested and the problem disappeared.
Apparently jqplot is the culprit and I found numerous entries referring to jqPlot memory leaks.
I use jQuery 1.6.4 and installed jqPlot Charts version 1.0.0b2_r792 which supposedly addresses memory leak issues.
Furthermore, I replaced
$('#chartdiv_bar').html('');
with
$('#chartdiv_bar').empty();
Thank you for your support.

Resources