How to call function method inside ajax success function? - javascript

How to call pagePresets.setFilter() inside $.ajax(){success} method?
self.setFilter.call('network', data.networks); returns
Uncaught TypeError: Cannot read property 'call' of undefined(…)
when self.setFilter('network', data.networks);
Uncaught TypeError: self.setFilter is not a function(…)
Code:
function pagePresets() {
this.loading = true;
this.isLoading = function () {
return this.loading;
};
this.setLoading = function (state) {
this.loading = state;
return;
};
/** this function loads saved filters */
this._loadFilters = function() {
jQuery.ajax({
type: 'post',
dataType: "json",
url: 'data.json',
success: function (data) {
//HOW TO CALL setFilter? this solution is not working
pagePresets.prototype.setFilter.call('network', data.networks);
}
});
};
}
pagePresets.prototype.setFilter = function (target, value) {
console.info(target + ' ' + value );
}

The call function takes as first argument a "context object". Take a deeper look at the call function here.
In the ajax callback function this or self doesn't refere to your class object anymore. And pagePresets is a function class with no static properties. So you need to get the object instance.
You need to specify which instance you want to call your prototype function with. I usualy declare a private property in my "class" wich holds a reference to the object for such scenarios where the context changes.
function pagePresets() {
//create a local variable here
var localInstance = this;
this.loading = true;
this.isLoading = function () {
return this.loading;
};
this.setLoading = function (state) {
this.loading = state;
return;
};
/** this function loads saved filters */
this._loadFilters = function() {
jQuery.ajax({
type: 'post',
dataType: "json",
url: 'data.json',
success: function (data) {
//Use the variable here to specify the correct context.
//the functions arguments need to be an array for the call function
pagePresets.setFilter.call(localInstance, [ 'network', data.networks ]);
}
});
};
}
pagePresets.prototype.setFilter = function (target, value) {
console.info(target + ' ' + value );
}

you can try to invoke that in the another function like this
function success() {
pagePresets.prototype.setFilter.call('network', data.networks);
}
function error() {
alert("error");
}
function searchEntity(id,userName, family) {
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080/mvc-test/rest/user/searchAll?pageNumber=1&pageSize=2&&orderBy=userName asc",
headers: {'X-CSRF-TOKEN': getMetaContentByName('_csrf')},
data : JSON.stringify({
"id":id,
"userName" : userName,
"familyName" : family
}),
dataType : 'json',
success : success,
error : error
});
}

Another way is to pass the parent context into the success method or delegate.
In the code below, onAjaxResponseReceived function is called with with the reference to the parent (class) context self from which other methods func1 and func2 can be accessed.
class TestClass{
constructor(searchUrl) {
this.searchUrl = searchUrl;
}
bind() {
self = this;
$.ajax({
url: self.searchUrl,
type:"POST",
data: data,
success: function (responseData) {
self.onAjaxResponseReceived(self, responseData);
}
});
}
onAjaxResponseReceived(self, data) {
self.func1(data);
self.func2(data);
}
func1(data) {
console.log('func 1');
}
func2(data) {
console.log('func 2');
}
}

Related

External method from an AJAX callback in JavaScript & jQuery

I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:
function ajaxCall(url, type, dataType, dataToSend, callback) {
if (dataType == undefined) dataType = "json";
if (dataToSend == undefined) dataToSend = null;
$.ajax({
url: url,
type: type,
dataType: dataType,
contentType: "application/json",
data: dataToSend,
async: true,
success: function (result) {
callback(result);
},
error: function (data, status) {
console.error("Server Error: " + status);
}
});
}
I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
showAjaxLoader(false); // Doesn't work
});
});
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
What am I doing wrong?
Thanks :)
Worked out some sample. this may be good practice. Try this :
$(document).ready(function() {
$("button").click(function() {registerUser();});
});
var Scallback = function(arg) {
alert("Success :"+arg);
showAjaxLoader(true);
}
var Ecallback = function(arg) {
alert("Err :"+arg);
showAjaxLoader(true);
}
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
function ajaxCall(url, type, Scallback, Ecallback) {
$.ajax({
url : url,
type : type,
async : true,
success : function(result) {
Scallback(result);
},
error : function(data) {
Ecallback(data)
}
});
}
function registerUser()
{
ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback);
}
Have you tried to do something like:
var that = this;
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
that.showAjaxLoader(false);
});
});
Declare your method like this
var obj = {
showAjaxLoader : function(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
}
Then inside ajax, call obj.showAjaxLoader(false); This may work.

Javascript - how to bind 'this' inside an ajax call to the object literal

I have an object literal router, containing an ajax call. I want to call other functions this.printMovies() inside the ajax call but this refer to the ajax object.
How do I escape it and make this refer to the router object itself?
var router = {
//...
init : function() {
this.getData("api/movies", "movies", callback);
},
getData : function (url, htmlType, callback) {
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); //'this' refers to ajax
this.printMovies(response, callback).bind(this) //still doesn't work
}
},
error: function (response) { console.log("Error:" + response); }
});
},
printMovies : function(){
},
}
Pass context option to ajax:
$.ajax({
context: this,
/* other options */
}
Now inside ajax callbacks, this will refer to router object.
Here in this case, the function getData holds the context of it's parent object in this keyword. So what you can do is, store the reference of this in some variable and use it later. like:
var router = {
//...
init : function() {
this.getData("api/movies", "movies", callback);
},
getData : function (url, htmlType, callback) {
var mainObj = this; // line to be noticed
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
if (response && response.length > 0) {
// parent object to be used
mainObj.printMovies(response, callback); //'this' refers to ajax
}
},
error: function (response) { console.log("Error:" + response); }
});
},
printMovies : function(){
}
}
Bind the entire success call back with bind it will work:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
A very common approach is to assign this to a local variable at the beginning of your function.
var self = this;
Then inside your callback use self instead of this:
self.printMovies(response, callback);
You can use the new ES6 arrow functions, or bind.
You might have to do this on your success or getData function
getData : function (url, htmlType, callback) {
...
}.bind(this),

jquery ajax store variable and then retrieve later on

Hi i am using jquery and ajax to retrieve the user id of the logged in user, Im saving this into a variable as I want to be able to do some logic with it later on. however I am having trouble accessing it. My code is below:
$(document).ready(function () {
var taskBoard = {
fetch: function (url, data) {
$('.loading-icon').fadeIn();
$('.task_board').addClass('loading');
$.ajax({
url: url,
async: true,
dataType: 'json',
data: data,
type: 'POST',
success: function (json) {
$('.loading-icon').fadeOut();
$('#task_board').html($(json.data.taskBoard));
$('.task_board').removeClass('loading');
$('.update-results').hide();
} // end success
}); //end ajax
}, //end fetch function
authUser: function (url, data) {
$.ajax({
url: url,
async: true,
dataType: 'json',
data: data,
type: 'POST',
success: function (json) {
$.each($(json), function (index, item) {
taskBoard.storeUser(item.id);
});
} // end success
}); //end ajax
}, //end authUser function
storeUser: function (param) {
var authUserId = param;
return param;
// if I do an alert here the correct user id is returned.
},
} //end var taskBoard
//However if I do an alert here outside of the var taskBoard I get an undefined.
alert(taskBoard.storeUser());
});
Any ideas how I can get this globally assigned variable outside of this function?
change this
storeUser: function (param) {
var authUserId = param;
return param;
// if I do an alert here the correct user id is returned.
},
change to this:
authUserId : null,
storeUser: function (param) {
if (param)
{
this.authUserId = param;
}
return this.authUserId;
},
Now the var authUserId will be stored as a property in the taskBoard object.
When param is undefined it will return the value unupdated if not it will update it first and then returns it.
A more elegant solution would be to use Object.defineProperty here.
Delete the storeUser property and after the declaration of the taskBoard object add this:
Object.defineProperty(taskBoard, "storeUser", {
get : function(){ return this.StoreUserVar; },
set : function(value){ this.StoreUserVar = value; }
});
Now you can assign the userid with:
taskBoard.storeUser = item.id;
//-------- taskBoard object
success: function (json) {
$.each($(json), function (index, item) {
taskBoard.storeUser = item.id;
doOtherFunction();
});
//--------
function doOtherFunction()
{
//the callback function fired from the success.
alert(taskBoard.storeUser); //this will alert with the value set.
}
Well if you need a global variable then declare that variable before the document.ready, since variables defined in this function are only valid in this function
Javascript Scope Examples

Execute callback function inside javascript object

I want to execute a callback function inside an object. I don't know if there is something wrong in the way I'm doing this.
I've googled for a solution, also searched on stackoverflow but couldn't find anything similar to the way I'm coding this.
PHPGateway.js
var PHPGateway = {
opt_friendlyURL: true,
opt_folder: 'ajax/',
callback_function: null,
useFriendlyURL: function (bool) {
this.opt_friendlyURL = bool;
},
setFolder: function (folder) {
this.opt_folder = folder;
},
send: function (service, method, data, callback) {
var url,
json_data = {};
if (this.opt_friendlyURL) {
url = this.opt_folder + service + '/' + method;
} else {
url = this.opt_folder + 'gateway.php?c=' + service + '&m=' + method;
}
if (data != undefined) {
json_data = JSON.stringify(data);
}
this.callback_function = (callback == undefined) ? null : callback;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success,
error: this.ajax_error
});
},
ajax_success: function (returned_object) {
if (this.callback_function != null) {
this.callback_function(returned_object.error, returned_object.data);
}
},
ajax_error: function () {
this.callback_function.call(false, {});
}
};
Then inside the HTML file that loads PHPGateway.js, I've the following code:
<script>
function submit_handler(event) {
event.preventDefault();
form_submit();
}
function form_callback(error, data) {
if(error == null) {
alert(data.text);
}
}
function form_submit() {
var data = {
status: $('#inStatus').val(),
amount: $('#inAmount').val(),
id: $('#inBudgetID'). val()
}
PHPGateway.send('budget', 'status', data, form_callback);
}
$('form').one('submit', submit_handler);
</script>
I get an error on this.callback_function(returned_object.error, returned_object.data);, the error is Uncaught TypeError: Object # has no method 'callback_function'.
What am I doing wrong?
Is this the best way to do it?
Thank You!
Based on minitech answer, I've updated PHPGateway.js like this. I've omitted the parts that weren't updated.
var PHPGateway = {
// Omitted code
send: function (service, method, data, callback) {
var url,
json_data = {},
that = this;
if (this.opt_friendlyURL) {
url = this.opt_folder + service + '/' + method;
} else {
url = this.opt_folder + 'gateway.php?c=' + service + '&m=' + method;
}
if (data != undefined) {
json_data = JSON.stringify(data);
}
this.callback_function = (callback == undefined) ? null : callback;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: function(data, textStatus, jqXHR) {
that.ajax_success(data, textStatus, jqXHR);
},
error: function(jqXHR, textStatus, errorThrown) {
that.ajax_error(jqXHR, textStatus, errorThrown);
}
});
},
ajax_success: function (data, textStatus, jqXHR) {
if (this.callback_function != null) {
this.callback_function(true, data.data);
}
},
ajax_error: function (jqXHR, textStatus, errorThrown) {
this.callback_function.call(false, {});
}
};
Now it works!!!
In your call to $.ajax, you need to add a context option:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
context: this,
success: this.ajax_success,
error: this.ajax_error
});
Your this variable in your Ajax success and error handlers are not pointing to the object you think they are. The context option to $.ajax() sets which object this points to in the Ajax callbacks.
Here’s your problem:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success,
error: this.ajax_error
});
When you set success and error to methods on this, they don’t keep their this. When a JavaScript function is called, it gets bound a this:
someFunction(); // this is undefined or the global object, depending on strict
someObject.someFunction(); // this is someObject
The built-in .call, .apply, and .bind of Function objects help you override this.
In your case, I think jQuery binds this to the Ajax object – a good reason to both not use jQuery and always use strict mode.
If you can guarantee or shim ES5 support, bind is an easy fix:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success.bind(this),
error: this.ajax_error.bind(this)
});
Which is equivalent to this if you can’t:
var that = this;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: function() {
that.ajax_success.apply(that, arguments);
},
error: function() {
that.ajax_error.apply(that, arguments);
}
});
And now, a tip for you: don’t namespace, and if you do, don’t use this. this is great for objects that are meant to be constructed. What would seem more appropriate is something like this, if you really have to:
var PHPGateway = (function() {
var callbackFunction;
var options = {
friendlyURL: true,
…
};
…
function send(service, method, data, callback) {
…
}
…
return { send: send };
})();

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:
var jqXHR = $.post('/dba/port.php', {
mode: "del_wallfunds",
pdata: cdata,
wname: wName
},
function (data) {}, "json")
.done(function (data) {
var msg = data.msg;
if (msg.indexOf("Error") == -1) {
alertify.success(msg);
delSelected(selGroup);
} else {
alertify.error(msg);
}
})
.fail(function () {
alertify.error("Error .....");
});
I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.
One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.
Any suggestions how to it in some elegant way?
Thanks
Either pass the done callback function as an argument when calling your function:
function ajaxCall(url, data, doneCallback) {
return $.post(url, data, doneCallback, "json").fail(...);
// or
return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
// do something
});
Or return the jqXhr object from the function, and assign the done callback then:
function ajaxCall(url, data) {
return $.post(url, data, function() {}, "json").fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
// do something
});
Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:
function ajaxCall(options) {
return $.ajax(options).fail(...);
}
var jqXhr = ajaxCall({
url: 'yoururl.php',
data: {key: 'value'},
dataType: 'json'
});
jqXhr.done(function(data) {
// do something
});
You can try to :
turn "request successfully returned a treatment error" into a "rejected request",
put the "alertify" processing in a common callback
Here is a sketch of what this could give :
function myAjaxApi(url, data){
var myAjaxCall = $.post(url, data, function (data) {}, "json")
.then(function (data) {
// using .then : change "request succesful with error state"
// to "rejected state"
var msg = data.msg;
if (msg !== undefined && msg.indexOf("Error") >= 0) {
var dfd = $.Deferred();
// try to match the same signature as the "error" option
dfd.reject(this, msg);
return dfd;
} else {
return data
}
});
myAjaxCall.done(function(data){
if (data.msg) {
alertify.success(data.msg);
}
}).fail(function (jqxhr, msg) {
if (!msg) { msg = "Error ....."; }
alertify.error(msg);
});
return myAjaxCall;
}
//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
delSelected(selGroup);
});
Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a common api.

Categories

Resources