I want to handle multiple ajax responses. Each request will take different time to complete.
Some request might be success and some might be failure . How to know which request is
success or failure ?
can anyone help me out to this one?
You can use JQuery $.ajax(..)
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
},
statusCode: {
404: function() {
alert('page not found');
},
200: function() {
alert('OK !');
}
}
});
or generar Error callback error : {}
Here is the solution,
var requestCount = 5,
requestComplete = 0,
onAjaxComplete = function () {
requestComplete++;
if (requestComplete >= requestCount) {
// all ajax requests complete
alert('Complete');
}
};
for (var i=0; i<requestCount; i++) {
Ext.Ajax.request({
// #todo: ajax request config
success: function () {onAjaxComplete();},
failure: function () {onAjaxComplete();}
});
}
Related
How to correctly abort an asynchronous ajax request? Whenever I click the stop button, the ajax is still running. Here is my code below:
My js
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
var xhr = $.ajax({
url: //url here,
type: 'GET',
async: 'true',
success: function(resultado) {
if (resultado.match("okay")) {
approved(resultado + "");
}
else {
removelinha();
}
$('#loaded').html(total);
}
}
);
$("#toStop").click(function () {
xhr.abort()
});
}, 3000 * index);
}
);
I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);
In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}
I'm trying to write some qunit unit tests for my knockout view models and I've run into an interesting issue.
In my view model I have the following function:
Get = function (id) {
return $.ajax({
url: API + "/" + id,
type: 'GET',
dataType: 'json',
timeout: Timeout,
statusCode: {
200: GetOneSuccess,
404: ItemNotFound
},
error: function () {
//Item(null);
}
});
},
Then in my unit test I have this:
vm.Get(vm.Item().Id()).then(function () {
ok(false, "Failure!");
},function () {
equal(vm.Item(), null, "Item was removed");
start();
});
ItemNotFound is as follows:
ItemNotFound = function () {
Item(null);
}
This is pretty straight forward, if the API controller returns "NotFound (Error 404)" set the Item to null. I am finding that my test if failing because when "then" is called the ItemNotFound function has not completed yet.
If I add a timeout to my unit test, it works:
vm.Get(vm.Item().Id()).then(function () {
ok(false, "Failure!");
},function () {
setTimeout(function () {
equal(vm.Item(), null, "Item was removed");
start();
}, 2000);
});
Anyone have any thoughts? Should I just not bother with the statusCodes and just handle all error types in the error handler? Doesn't seem as elegant.
Error handlers are fired first before the status code functions are fired. The "then" function takes a "success callback" and an "error callback". So in essence, your error (fail) is firing before the statuscode "notfound" fires.
When you are setting up a timeout, the function returns immediately, fires your status code and then based on your set timeout, fires that specific code.
If you still want the code structure you have then here is how I would do it. Your GET function should return a Deffered promise object that encapsulates the actual ajax call and don't specify a success or error handler and call your success or error functions first from your statusCode.
I have created a fiddle for the same
http://jsfiddle.net/sujesharukil/BWA9D/15/
var data = {
json: $.toJSON({
text: 'some text',
array: [1, 2, 'three'],
object: {
par1: 'another text',
par2: [3, 2, 'one'],
par3: {}
}
})
}
var callEcho = function(url) {
return $.Deferred(function(def){
$.ajax({
url: url,
type: "POST",
data: data,
statusCode: {
200: function(data,xhr){
GetOneSuccess();
def.resolve(data);
},
404: function(xhr){
ItemNotFound();
def.reject();
}
}
});
}).promise();
};
function GetOneSuccess(){
alert('Get One success Called');
}
function ItemNotFound(){
alert('Item Not Found Called');
}
var testFunc = function(url){
var js = callEcho(url);
js.done(function(data){
alert(JSON.stringify(data) + ' done function called');
});
js.fail(function(){
alert('fail function called.');
});
}
//fire the success
testFunc("/echo/json/" );
//fire the fail
testFunc("/echo/jso/");
I have auto request using jquery ajax, I am using this function for detection new chat message & notification case. Sometimes I am thinking again what is the effect if client auto request without finish,
I am worried my server is down because i think this is like DDOS HTTP Throttling.
This is my code
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat() {
setTimeout("notifChat()" ,2000);
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg) {
//to do success
}
});
setTimeout("notifChat()" ,2000);
}
My question is
Is possible to down server or make server hung up ?
If it is not better idea any somethink suggestion ?
Note: This is not production ready code, I have not tested it.
A couple weekness of this code:
It does not handle the two http connection limit
strengths:
it can tell if the server return an error (as in server error 404,403,402....)
var failed_requests = 0;
var max = 15;
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat()
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg)
{
//to do success
},
complete: function()
{
// either call the function again, or do whatever else you want.
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
failed_requests = failed_requests + 1;
if(failed_requests < max)
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
else
{
alert('We messed up');
}
}
});
}