jquery ajax store variable and then retrieve later on - javascript

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

Related

Why does my jquery plugin cannot access or utilize a data or vaiable from my script?

I have this custom made jQuery plugin, whenever I called it in my script, the option parameter row cannot access the variable or data defined on my script.
JQuery Plugin:
{
$.fn.dbGrid = function (options) {
var settings= $.extend({
read: function () { },
row:""
}, options)
settings.read.call(this)
//console.log(settings.row)
//It ouputs nothing
}
Usage on my Script:
var rows;
function onSuccess(data) {
rows = data;
}
function populateTable() {
$("#container").dbGrid({
read: function () {
$.ajax({
url: "some url",
success: onSuccess,
dataType: "json",
async: false,
type: "GET"
});
},
row:rows
//here the option `row` can not access my `rows` defined in my script, thats why it cannot yield result in my plugin whenever I do console.log
})
//console.log("Row in Base script" + rows);
//Here it outputs the result I want which is data from the function onSuccess
}
populateTable();
}

How to call function method inside ajax success function?

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

Knockout.js Observable Array with onlick event

Hi I have a web application, I'm very new to KnockOut.js
I have my JS COde
ko.applyBindings(new LOBViewModel());
//COMMENTED SECTION BINDS THE DATA TO HTML, BUT DOES NOT TRIGGER ONLICK EVENT
//function LOBViewModel() {
// var self = this;
// self.vm = {
// LOBModel: ko.observableArray()
// };
// GetLOB();
//
// self.DeleteRecord = function (lobmodel) {
// $.ajax({
// type: "POST",
// url: '/Admin/DeleteLOB',
// data : {LOB_ID : lobmodel.LOB_ID},
// success: function (data)
// {
// alert("Record Deleted Successfully");
// GetLOB();//Refresh the Table
// },
// error: function (error)
// {
// }
// });
// };
// function GetLOB() {
// $.ajax({
// url: '/Admin/GetLOB',
// type: "POST",
// dataType: "json",
// success: function (returndata) {
// self.vm.LOBModel = returndata;
// ko.applyBindings(self.vm);
// alert("Hello");
// },
// error: function () {
// }
// });
// };
//}
//UNCOMMENTED SECTION DOES NOT BIND THE DATA TO HTML
function LOBViewModel() {
var self = this;
self.LOBModel = ko.observableArray([]);
GetLOB();
self.DeleteRecord = function (lobmodel) {
$.ajax({
type: "POST",
url: '/Admin/DeleteLOB',
data: { LOB_ID: lobmodel.LOB_ID },
success: function (data) {
alert("Record Deleted Successfully");
GetLOB();//Refresh the Table
},
error: function (error) {
}
});
};
function GetLOB() {
$.ajax({
url: '/Admin/GetLOB',
type: "POST",
dataType: "json",
success: function (returndata) {
self.LOBModel = returndata;
alert(self.LOBModel.length);
},
error: function () {
alert("eRROR GET LOB");
}
});
};
}
Details
My Json is in the following format
[0] = > { LOB_ID : 0 , LOB_Name : "data" LOB_description : "data" }
[1] => and so on
HTML File
<tbody data-bind="foreach: LOBModel">
<tr>
<td data-bind="text:LOB_ID"></td>
<td data-bind="text: LOB_Name"></td>
<td data-bind="text: LOB_Description"></td>
<td><button data-bind="click: $root.DeleteRec">Delete</button></td>
</tr>
</tbody>
My Question is
why is that
i have to use vm to bind the json into LOADModel so that it works, when i use self.LOBModel = ko.observableArray([]); the binding does not happen. i.e, my table does not load the data.
my Onlick does not get triggered in both the version of the code, I've tried self.DeleteRec, $root.DeleteRec and just DeleteRec as well. Though seems very obvious it just doesnot work.
Would the DeleteRec know which record i'm deleting. is lobmodel.LOB_ID correct way to use ?
To answer point by point:
(1) Your problem is in the GetLOB function, on this line:
self.LOBModel = returndata;
By doing that, you overwrite the self.LOBModel = ko.observableArray([]). What you should do instead is this:
self.LOBModel(returndata);
Then you should see the data in your table (if you have no other errors). The thing to remember here, is that if you make a variable observable, you always need to use the ()-syntax to read or write the underlying value. If you use = instead, you erase the observable functionality.
(2) the approach with '$root.DeleteRecord' is correct. 'self.DeleteRecord' would not work, and neither would just DeleteRecord. What would also work is '$parent.DeleteRecord'. The problem seems to be that you do 'DeleteRec' instead of 'DeleteRecord'.
(3) your approach is the right one. Deleted my others comments on this point, since Richard Dalton below me made a correct comment that invalidates what I typed here.
Edit: working Fiddle
http://jsfiddle.net/LFgUu/4/

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.

After parsing xml I am getting undefined as a result [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Keeps saying result property is not defined. Why?
I am parsing xml and what I want is to return xml after parsing it. The problem is that in my getResult() function result has a value of undefined. Why and how can I make it work?
Here is my code
var result = '';
var Xml = {
to : null,
from : null,
url : null,
init: function (fromaddress, toaddress, link) {
from = fromaddress;
to = toaddress;
url = link;
this.requestXml();
return this;
},
requestXml: function () {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: this.parseXml
});
},
parseXml: function (xml) {
console.log('xml: ' + $(xml));
result = $(xml);
},
getResult: function () {
console.log('Result: ' + Xml.result); //<--- Here result has undefined value
return result;
}
};
Xml.result is never being set. Maybe I'm missing something, but you will need to do this in parseXml in order to set its result field:
this.result = $(xml);
And in getResult your console.log call shouldn't show undefined. You can even have it return this.result.
Another thing, in your initializer, you should be setting each property with the "this" keyword.
Here is how I solved my issue
var Xml = function () {
var to, from, url, result,
init = function (fromaddress, toaddress, link, callback) {
from = fromaddress;
to = toaddress;
url = link;
requestXml(callback);
},
requestXml = function (callback) {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: callback
});
},
getResult = function () {
return result;
};
return {
init : init,
getResult : getResult
};
};

Categories

Resources