Execute success ajax from method object via dynamic function - javascript

I need to run the success of ajax from a method function of object, this work when a pass to normal variable function
methodOne = function(data) {
alert(data);
};
$(document).on('click', ".clichere", function() {
var callback = function(){};
callback = methodOne;
runAjax({dispatch_ajax : "testing"}, callback );
});
function runAjax(data, succFunction) {
$.ajax({
type: "POST",
data: data,
success: succFunction,
error: function(error) {
alert(JSON.stringify(error));
},
});
}
this not work
var myapp = function() {
this.listTableOptions = function(data) {
alert(data);
};
};
$(document).on('click', ".clichere", function() {
obj = new myapp();
runAjax({dispatch_ajax : "testing"}, obj.listTableOptions() );
});
I can't not get the data in myapp object

You want to pass the function listTableOptions instead of executing it and passing the result so the following will work:
var myapp = function() {
this.listTableOptions = function(data) {
alert(data);
};
};
$(document).on('click', ".clichere", function() {
obj = new myapp();
runAjax({dispatch_ajax : "testing"}, obj.listTableOptions );
});
Notice obj.listTableOptions instead of obj.listTableOptions()

Related

How to call the callback function with class name defined in another javascript file

I was trying to call the callback function with classname, defined in another javascript file, but I was failed to call. I didn't get the mistake I did. Please let me know the mistake I did in below code and Thank you show much for your help.
I have created one central javascript file like below
CentralScript.js
function CentralScript() {
}
CentralScript.prototype.makeRequest = function (className, cbf, dataToSend) {
$.ajax({
url: 'apiurl',
type: 'POST',
dataType: 'json',
data: {
parameters : dataToSend
},
success: function (responseData) {
this.showResponse(className, cbf, responseData);
},
complete: function() {
},
error: function () {
console.log("Error occurred...");
}
});
};
CentralScript.prototype.showResponse = function (className, cbf, data) {
className.cbf(data);
};
and I have created another file like below
SomeFile.js
function SomeFile() {
}
SomeFile.prototype.sayHi = function() {
var obj = new CentralScript();
var dataToSend = {
method: 'someMethod'
};
obj.makeRequest('SomeFile', 'resultToShow', dataToSend);
};
SomeFile.resultToShow = function (data) {
console.log(data);
};
and I have created main.js file like below
main.js
var ProjectName= (function() {
var sfObj;
function init() {
createObjects();
initiateProject();
}
function createObjects() {
sfObj = new SomeFile();
}
function initiateProject() {
sfObj.sayHi();
}
return {
init : init
};
})();
$(ProjectName.init);
I was getting the response when I was making ajax request from SomeFile.js file, but the response was not logging in console.
I am getting 'cbf' as undefined in 'showResponse' function present in CentralScript.js file
CentralScript.prototype.showResponse = function (className, cbf, data) {
className.cbf(data);
};
May I call the callback function like this "className.cbf(data);" present in SomeFile.js
Please let me know the mistake I did and Thank you show much for your help.
The problem has nothing to several files.
This is corrected script:
//CentralScript.js
function CentralScript() {
}
CentralScript.prototype.makeRequest = function (className, cbf, dataToSend) {
var $this = this;//save for further use
$.ajax({
url: 'apiurl',
type: 'POST',
dataType: 'json',
data: {
parameters: dataToSend
},
success: function (responseData) {
//cbf(responseData);//cbf is SomeFile.resultToShow
$this.showResponse(className, cbf, responseData);//this is $.ajax here
},
complete: function () {
},
error: function () {
console.log("Error occurred...");
}
});
};
CentralScript.prototype.showResponse = function (className, cbf, data) {
//className.cbf(data);//undefined
cbf(data);//cbf is SomeFile.resultToShow
};
//SomeFile.js
function SomeFile() {
}
SomeFile.prototype.sayHi = function () {
var obj = new CentralScript();
var dataToSend = {
method: 'someMethod'
};
//obj.makeRequest('SomeFile', 'resultToShow', dataToSend);
obj.makeRequest(this, this.resultToShow, dataToSend);//this is SomeFile
};
SomeFile.prototype.resultToShow = function (data) {//need .prototype to add function to SomeFile
console.log(JSON.stringify(data));
};

How to override the jQuery.ajax success function after it has been initialized?

A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request's success function with another one.
Basically I want to do this:
var ajaxRequest = null;
jQuery('#mybutton').click(function () {
if (ajaxRequest) {
ajaxRequest.success = function () {
};
}
ajaxRequest = jQuery.ajax({
url: '...',
success: function () {
console.debug('do something');
}
});
});
But the initial success handler is been called.
How to achieve an override?
You can try the following hack, I have tested it with asynch setTimeout (instead of asynch jQuery.ajax) and it works -
var mySuccessHander = function() {
console.debug('Initial function');
}
var test = jQuery.ajax({
url: '...',
success: function() {
mySuccessHander();
}
});
And when the button is clicked for the second time, execute following -
mySuccessHander = function() {
console.debug('Overridden function');
}
Nice question , this will work..
var isRequestDone = true;
jQuery('#mybutton').click(function () {
var requestParams = {
url: '....',
beforeSend: function () {
isRequestDone = false;
},
success: function () {
isRequestDone = true;
console.debug('do something');
},
error: function () {
isRequestDone = true;
}
}
if (!isRequestDone) {
requestParams.success = function () {
console.log('please wait for a while!');
};
}
jQuery.ajax(requestParams);
});
beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.
You can set the ajax arguments to a variable first so you can modify it later on.
var clicks = 0,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}
};
$('#myButton').click(function() {
++clicks;
if (clicks > 1) {
// set the success function if clicked more than once
ajaxArgs.success = function () {
console.debug('Success function ' + clicks);
}
}
$.ajax(ajaxArgs);
});
If you want to modify the success function only when ajax is still loading you can do this:
var loading = false,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}, complete: function () {
loading = false;
}
};
$('#myButton').click(function() {
if (loading) {
// set the success function if ajax is still loading
ajaxArgs.success = function () {
console.debug('Another Success function ');
}
} else {
loading = true;
$.ajax(ajaxArgs);
}
});

Creating dojo javascript function with callback

I have a dojo class like this.
var widget = declare("app.util",null, {
createSecuredLayers: function () {
$.ajax.get({
url: "/Api/GetLayer",
success: function (e) {
},
error: function () {
}
});
}
});
I want to use this object with callback parameters. I mean I want to pass success and error callbacks as parameter.
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
createSecuredLayers: function(item) {
$.ajax.get({
url: "/Api/GetLayer",
success: item.successCallback,
error: item.errorCallback
});
}
When you call the method, don't forget to pass the response in the success callback.
util.createSecuredLayers({
successCallback: function(resp) {},
errorCallback: function(err) {}
});
You can do it like this:
var widget = declare("app.util",null, {
createSecuredLayers: function (args) {
$.ajax.get({
url: "/Api/GetLayer",
success: args.success,
error: args.error
});
}
});
var util = new app.util();
util.createSecuredLayers({
success:function(){ },
error:function(){ }
});
You should also consider using Dojo's deferred

TypeError: this.functionName is not a function

So I have created a small javascript class that is supposed to AJAX post something in a PHP file. The class is the following:
var cms = cms || {};
cms.load_view = (function() {
return {
change: function() {
jQuery("#layout-switch a").on('click', function()
{
jQuery('#layout-switch a').removeClass('current');
jQuery(this).addClass('current');
var column_number = jQuery(this).attr('data-name');
var category = jQuery("#cat_id").val();
var data = {mode: column_number, cid: category};
this.postChange(data);
});
},
postChange: function(data) {
jQuery.ajax({
type: 'post',
url: SITEURL + "/modules/digishop/loadcategory.php",
data: data,
beforeSend: function () {
jQuery('#digishop').animate({
opacity: 0
}, 250, function () {
jQuery(this).addClass(column_number);
jQuery(this).animate({
opacity: 1
}, 250);
});
},
success: function (html) {
jQuery("#digishop").html(html);
}
});
return true;
}
}
})(jQuery);
jQuery(document).ready(function() {
cms.load_view.change();
});
However, when I click the selector Firebug says that postChange is not a function when it is called in the first method, a.k.a. this.postChange(data);
Any ideas?
Thanks!
Inside the change function, this is a reference to the link you clicked. Replace this.postChange(data); with cms.load_view.postChange(data);.

Access class variable in jquery

I have a select in my html and would like to add the options via ajax when the page loads. The options values are in my DB and I get them via a call to ajax. To do so, I'm writing a class in javascript but I just can't get my data when it runs. Please take a look :
--- Main.js ---
function MyLoader() {
this._clients = null;
this._code = null;
}
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
}
});
},
getCode: function() {...}
};
Then I have the following :
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
alert(loader._clients);
//Here I want to add my options to the select
});
My alert always returns null, and I don't understand why. I need to save my data in the class in order to access them anytime I need to.
Can you point me to the right direction to make all my stuff work ? Thank you for your answers.
Loader.prototype = { // v---callback parameter
loadClients: function(callback) {
$.ajax({
url: "my/php/",
context: this, // <---set success context
type: "POST",
data: {...},
success: callback // <---pass callback
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
// v---pass callback
loader.loadClients(function(response) {
this._clients = response;
alert(this._clients);
//Here I want to add my options to the select
});
});
I believe that you need to do all of your dynamic loading inside of your 'success' callback, since it is loading asynchronously.
You need to do it inside the success callback since it's async:
Loader.prototype = {
var context = this;
loadClients: function() {
$.ajax({
url: "my/php/",
type: "POST",
data: {...},
success: function(response) {
context._clients = response;
alert(loader._clients);
//Here I want to add my options to the select
}
});
},
getCode: function() {...}
};
$(document).ready(function() {
var loader = new Loader();
loader.loadClients();
});

Categories