mootools ajax request aborts sporadically (onFailure) - ajax

I have a javascript function called when the page loads. It just gets some user data through an ajax call and checks some checkboxes based on the user id's returned.
window.onload=function(){
getBlockedUsers();
}
function getBlockedUsers(){
var deptID = $('deptID').value;
var request_data = 'DeptID='+deptID;
var req = new Request.JSON({
url:'/ajax/getuserData.cfm',
method: 'post',
noCahe: true,
data: request_data,
onSuccess: function(response)
{
var jLength = response.json.length;
for(i=0;i<jLength;i++){
var user_id = response.json[i].id;
if($('user_'+user_id)){
$('user_'+user_id).checked = true;
}
}
},
onFailure: function (xhr)
{
alert('There was an error while trying to fetch data');
},
onException: function (xhr)
{
alert('There was an exception while trying to fetch data');
}
}).send();
}
I keep getting the alert in the onFailure() function for some reason and when I inspect the ajax call, it appears to be aborted. This does not happen all the time. Happens in IE9.
I had the function call within domReady but moved to onload thinking it would help but it's still the same. Any ideas on why this might be happening would really help.

Related

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Ajax calls and JQuery: stop previuos ajax calls

In a jsp page, when a user clicks a button, an ajax call is triggered.
If the user clicks again and again the button, I would that only the last ajax call be valid and only its response be considered.
I use:
var lastRequest=null;
$('#button').click(function() {
if (lastRequest) {
lastRequest.abort();
lastRequest = null;
}
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
With Firebug, I see that some request are aborted, but not all.
I think that if an ajax call is triggered, it's not possible to ignore the response, is it?
EDIT
If I set a var in MyAction.do and I read it in the success callback, is it possible to have a conflict in the success callback?
In case, how could I prevent that behaviour?
My experience with aborting ajax-calls is that it can be pretty random when it works.
A workaround that I've used once or twice is counters:
var lastRequest=null;
var started = 0, finished = 0;
$('#button').click(function() {
++started;
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
//Only do stuff on the last active request
if(++finished == started)
response= $('<div/>').append(response);
}
});
});
use object.abort() to discard data that have been called by service
i have add the code as to click on a button to abort service you can try it with respect to your case :)
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
$(document).click(function() {lastRequest.abort() });

Call ajax inside a custom method and return ajax result to called method

in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}

Putting a JSON response into a hidden field and retrieving it into a function

I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the above function that makes a JSON request.
var rows=$("#rows").val();
alert("rows = "+rows);
return false;
});
});
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).
Also tried to replace the preceding function with the following.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the first function that makes a JSON request.
var form = $(this),
url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
return false;
});
});
But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.
Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback) // <==== Accept the callback
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
callback(); // <==== Call the callback
},
error: function(e)
{
alert('Error: ' + e);
callback(); // <==== Probably want to give it a value telling it things failed
}
});
}
Then using it:
$(function() {
$('#dataForm').submit(function() {
var form = $(this); // <== Grab this outside the callback
rowCount(function() {
var url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
});
return false;
});
});
If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources