Ajax request, how to call an other function than "success" one's? - ajax

I use JQuery Ajax function :
$.ajax({
url: ...,
success: function (){
...
},
...
});
I need to execute some code just before every call of the success function (but after the response has been received).
I suppose that this success function is triggered like an event, so is there a way to make an other function call in place of success one's?

You can use the Global Ajax Event Handlers methods to do this.
Sounds like you might want to use AjaxComplete:
$(document).ajaxComplete(function(){
// do something here when ajax calls complete
});
Be warned -- this will occur for EVERY jQuery ajax call on the page...

You could also call that other function right at the biginning of done:
$.ajax({
url: ...,
done: function (){
someOtherFunction();
},
...
});
This should pretty much accomplish what you described in your question.

Is beforeSend what you are looking for:
$.ajax({
url: "...",
beforeSend: function (x) {
//do something before the the post/get
}
}).done(function (data) {
//done code
});

I succeed in calling an other function just before success one by replacing $.ajax() by a custom function like :
function mYajax(options) {
var temporaryVariable = options.success;
options.success = function () {
console.log('Custom')
if (typeof temporaryVariable === 'function')
temporaryVariable()
};
return $.ajax(options);
}
$('button').click(function () {
mYajax({
url: "/echo/json/",
data: {
foo: "bar"
},
success: function (data, textStatus, jqXHR) {
console.log('succeed action');
},
});
});

Related

Ajax .done function is executing before success in Laravel project

The alert from done function is executing before success. Please help me. What am I doing wrong here:
function load_organization()
{
return $.ajax({
url: '/partials/structure',
method: "GET",
data: {id:id},
success: function (data) {
$(data.organizations).each(function(index, organization) {
$("#organization").append(new Option(organization));
});
}
});
}
$(document).ready(function(){
load_organization().done(function(){
alert('Success');
});
});
"Done" is a callback triggered from a running XHR instance with jQuery.
The doc says:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
Take a look:
function load_organization()
{
$.ajax({
url: '/partials/structure',
method: "GET",
data: {id:id},
success: function (data) {
$(data.organizations).each(function(index, organization) {
$("#organization").append(new Option(organization));
});
}
})
// Use done here -> look official API doc for some explanations: http://api.jquery.com/jQuery.ajax/
.done(function(){
alert('Success');
});
}
$(document).ready(function(){
load_organization();
});
Hope this could help you in your solution
You are executing alert('Success'); when load_organization() is called. so irrespective of ajax, the message is displaying. You can alert the success in same single function. And .done() has only one callback and it is the success callback.
function load_organization()
{
return $.ajax({
url: '/partials/structure',
method: "GET",
data: {id:id},
success: function (data) {
$(data.organizations).each(function(index, organization) {
$("#organization").append(new Option(organization));
alert('Success');
});
}
});
}

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

using On success function in Jquery Ajax call

I have a .js class named Widget.js
In widget.js class I am initiating a errors.ascx control class that has a JS script function "GetErrors()" defined in it.
Now, when I call GetErrors from my widgets.js class it works perfectly fine.
I have to populate a few controls in widgets.js using the output from GetErrors() function.
But the issue is that at times the GetErrors() takes a lot of time to execute and the control runs over to my widgets class. and the controls are populated without any data in them.
So the bottom line is that I need to know the exact usage of the OnSuccess function of Jquery.
this is my errors.ascx code
var WidgetInstance = function () {
this.GetErrors = function () {
$.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false,
success: function (result) {
result = (typeof (result) == "object") ? result : $.parseJSON(result);
loggedOnUsers = result;
}
});
},.....
The code for the Widgets.js file is
function CreateWidgetInstance() {
widgetInstance = new WidgetInstance();
widgetInstance.GetErrors();
}
now I want that The control should move from
widgetInstance.GetErrors();
only when it has produced the results.
any Help???
You can use jQuery Deferreds. $.ajax() actually returns a promise. So you can do the following:
var WidgetInstance = function () {
this.GetErrors = function () {
return $.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false
});
},.....
Then you can process the results like so...
widgetInstance.GetErrors().done(function(result){
//process the resulting data from the request here
});
Hi Simply use async:false in your AJAX call.. It will block the control till the response reaches the client end...
var WidgetInstance = function () {
this.GetErrors = function () {
$.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false,
async: false,
success: function (result) {
result = (typeof (result) == "object") ? result : $.parseJSON(result);
loggedOnUsers = result;
}
});
},.....
I did a simple solution for this..
I just called my populating functions in the onSuccess event of the GetErrors() of my control and everything worked perfectly..

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

How to get the result of a jQuery AJAX call then call another function

Basically I am trying to call a function (function 1), that get the results from another function (function 2). And this function 2 is making an ajax call.
So the code would be like this:
function f1 () {
var results = f2();
}
function f2() {
$.ajax({
type: 'POST',
url: '/test.php',
success: function(msg){
}
});
}
I know that is I display an alert in the success function, I get the results. But how can we make this result be sended back?
I tryed to do something like this inside function 2 without success:
return msg;
thanks for your help
In theory, this is possible using jQuery's async: false setting. That setting makes the call synchronous, i.e. the browser waits until it's done.
This is considered bad practice, though, because it can freeze the browser. You should re-structure your script so you can do the relevant things in the success callback instead of f1. I know this is less convenient than what you do in f1(), but it's the right way to deal with Ajax's asynchronous nature.
You can forcefully make the request synchronous ( kinda losing the benefit of ajax ) but making your code work:
function f2() {
var ret = false;
$.ajax({
type: 'POST',
url: '/test.php',
async:false,
success: function(msg){
ret = msg
}
});
return ret;
}
Otherwise, you have to add a callback in your success function if you want to keep it asynchronous..
function f2() {
$.ajax({
type: 'POST',
url: '/test.php',
async:false,
success: function(msg){
doSomething(msg);
}
});
}

Resources