How to use ajaxmanager with jquery ajax request? - ajax

I'm trying to use the ajax blockmanager plugin to manage my jquery ajax requests, but I'm not sure how to implement it...
// Follow button click event
$('#loginBtn').click(function () {
var that = this;
var request = {
'username': $('#txtUsername').val(),
'password': $('#txtPassword').val()
};
var params = $.toJSON(request);
ajaxManager.add($.ajax({
type: "POST",
url: "ajax/Login.aspx/Login",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d === true) {
window.location = "dashboard.aspx";
}
else {
$('#errorMessage').slideDown();
}
}
}));

I know it's a bit outdated question... But if anyone comes across this issue:
You are passing the already created/started request as a parameter to the manager.
You should only pass its options. The request will be created and handled by the manager.
ajaxManager.add({
type: "POST",
url: "ajax/Login.aspx/Login",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d === true) {
window.location = "dashboard.aspx";
}
else {
$('#errorMessage').slideDown();
}
}
});

Do you have ajaxManager instantiated?
//create an ajaxmanager named cacheQueue
var ajaxManager = $.manageAjax.create('cacheQueue', {
queue: true,
cacheResponse: true
});

You first create the manager
this.ajaxManager = $.manageAjax.create("aiapi", {
queue: true,
cacheResponse: true,
maxRequests: 3,
abort: this.abortCallback
});
where the queue of calls is active, max concurrent requests are 3, and the caching is enabled. The common abortCallback is like
this.abortCallback = function (response) {
Logger.log("APIManager.abortCallback " + Utils.toString(response));
};
It's convenient to add the common ajaxSetup setup like
$.ajaxSetup({
cache: true,
timeout: 10 * 1000
});
Here you can see the response timeout in msec set to 10 sec.
You then do a GET like
this.DoGet = function (url, method, timeout) {
return new Promise((resolve, reject) => {
var options = {
type: 'GET',
url: url + method,
contentType: "application/json",
timeout: (15 * 1000) // sets timeout to 60 seconds
};
if (timeout) options.timeout = timeout;
const errorCallback = function (error) {
console.error(error);
return reject(error);
};
const successCallback = function (data) {
return resolve(data);
};
const completeCallback = function (data) {
return resolve(data);
};
options.error = errorCallback;
options.success = successCallback;
//options.complete= completeCallback;
$.manageAjax.add("default-queue", options);
/*$.ajax(options)
.done(function (data) {
return resolve(data);
})
.fail(function (error) {
console.error(error);
return reject(error);
})
.always(function () {
// called after done or fail
});*/
});
You can see in the comment the version without the ajax manager. And it the same way to POST is like
this.DoPost = function (url, method, body, timeout) {
try {
body = JSON.stringify(body);
} catch (error) {
console.error(body);
return reject(error);
}
return new Promise((resolve, reject) => {
var options = {
type: 'POST',
url: url + method,
data: body,
contentType: "application/json",
dataType: 'json',
timeout: (15 * 1000) // sets timeout to 60 seconds
};
if (timeout) options.timeout = timeout;
const errorCallback = function (error) {
console.error(error);
return reject(error);
};
const successCallback = function (data) {
return resolve(data);
};
options.error = errorCallback;
options.success = successCallback;
$.manageAjax.add("default-queue", options);
/*$.ajax(options)
.done(function (data) {
return resolve(data);
})
.fail(function (error) {
console.error(error);
return reject(error);
})
.always(function () {
// called after done or fail
});*/
});
}//DoPost
The important thing here is the name of the ajax queue when adding a new GET / POST request via the api
$.manageAjax.add("default-queue", options);
This means basically that you can have one or more queues, that improves your requests parallelism.

Related

Ajax is not aborting

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);
}
);

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

Common beforeSend in Ajax call and abort if conditions not satisfied

I am trying to write a common functionality to all Ajax call as below.
The abort is not working when I write it separately like below,it works if I add the beforesend in the same ajax as below, which is commented
$(document).ready(function () {
$.ajax({
beforeSend: function (jqXHR, settings) {
check = TestCallMethod();
if (check.responseText != "true") {
alert("Call Failed");
jqXHR.abort(event);
}
}
});
$.ajax({
// beforeSend: function (jqXHR, settings) {
// debugger;
// check = TestCallMethod();
// if (check.responseText != "true") {
// alert("Call Failed");
// jqXHR.abort();
// }
// },
cache: false,
url: '#Url.Action("TestCall2", "Home")',
success: function (data) {
alert(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
function TestCallMethod()
{
return $.ajax({
url: '#Url.Action("TestCall", "Home")',
async: false,
cache: false,
success: function (data) {
return data;
},
error: function (request, status, error) {
alert(request.responseText);
return false;
}
});
}
How to achieve the abort for common ajax beforsend?
You can apply common settings to global on Ajax . I hope it would be helpful.
$.ajaxSetup({
global: true,
beforeSend: function (jqXHR, settings) {
check = TestCallMethod();
if (check.responseText != "true") {
alert("Call Failed");
jqXHR.abort(event);
}
}
});

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

Resources