Passing data to a function as a key and value - javascript

I have been trying to execute a function as follows, but am not succeeding.
var leagueSelect = "allLeagues";
loadTable("#loadLeaguesTable","php/leagueTable.php",'leagueSelect',leagueSelect);
The loadTable function:
function loadTable(tableDiv, tableURL, tableType, tableVal){
$.post(tableURL,{tableType:tableVal},function(data){
$(tableDiv).append(data);
});
}
I'm trying to send the values in the post in this format: { leagueSelect: leagueSelect }.
If I hard-code leagueSelect into my function in place of the tableType parameter in the $.post function, it works.
How am I supposed to send 'leagueSelect' properly in my function call?
I'm thinking the data[key] = value method but I didn't get that working either.
Thanks.

When you assign the variable you're actually creating a new object with the property tableType set to whatever the tableVal value is.
Instead you need to use the object[key] = val; syntax or pass the post data in directly like this:
var leagueSelect = "allLeagues";
loadTable("#loadLeaguesTable", "php/leagueTable.php", { leagueSelect: leagueSelect });
function loadTable(tableDiv, tableURL, postData) {
$.post(tableURL, postData, function(data) {
$(tableDiv).append(data);
});
}

Related

manipulate vue.js data parameter from within sub method

I know that I can change the value of a vue data value from within a method by using this.variable_name. But when I'm trying to do this from within a method with a sub-method (because I'm making an ajax request) I am getting an undefined error.
I have something like
var myvue = new Vue({
name: "MyVue",
el: '#my-vue-id',
data: {
fields: field_list // this is set in another js method elsewhere
},
methods: {
reject: function (index, objectid) {
if (confirm("Are you sure?")) {
$.get("/reject/" + objectid, function (data) {
if (data.success == true) {
$("#" + objectid).fadeOut(400, function() {
this.field_list.splice(index, 1);
});
} else {
alert('Failed to delete.');
}
});
}
}
}
});
I also tried setting var self = this; within the $.get method, then trying to splice self.field_list but in both cases I get an error Cannot read property splice of undefined
EDIT since I may have been unclear-- the field_list is being populated. If I were to do this.field_list.splice outside the ajax function, it works fine. The issue is just how to access external scope from with the vue methods.
A callback function does not get your Vue instance as its context (this) when it is called. Use arrow functions for your callbacks, or save this to a variable and use that.
You need to do the var self = this; outside of the $.get method (before it) as within the $.get method you have a different scope, and that is the root of the problem. Then within the $.get method use self.field_list.splice(index, 1);

How to pass a parameter to a function that is passed to another function as string?

I have the following piece of code :
accountSelector.executeInParallel('processAccounts', 'postProcess');
function processAccounts() {
return JSON.stringify(syncMasterLists());
}
And instead of having this, I want to be able to pass a value to the processAccounts accounts function.
For the purpose I changed the code so it's looking like this now :
accountSelector.executeInParallel('processAccounts("DE")', 'postProcess');
function processAccounts(arg) {
return JSON.stringify(syncMasterLists());
}
Unfortunately, after introducing the change I started getting the following error :
Cannot find function processAccounts("DE").
I cannot understand am I doing this wrong(and if yes then what is wrong) or it's just something that can't be done.
I cannot understand am I doing this wrong(and if yes then what is
wrong) or it's just something that can't be done.
accountSelector.executeInParallel takes the function name as parameter and execute the same, processAccounts("DE") is not a valid function name or the name of the function that exists.
As per documentation, there is a way to pass optionalInput parameter
The input, if specified by optionalInput, will be passed into the
function specified by functionName
accountSelector.executeInParallel(functionName, optionalCallbackFunctionName, optionalInput)
In your case, it will be
accountSelector.executeInParallel('processAccounts', 'postProcess', 'DE' );
Why don't you call the function first and replace the result in the 'executeInParallel' method as follows:
var res = processAccounts("DE");
accountSelector.executeInParallel(res, 'postProcess');
function processAccounts(arg) {
return JSON.stringify(syncMasterLists());
}
Some closure can probably solve your problem, depends on how accountSelector.executeInParallel is implemented
const accountSelector = {
executeInParallel(pre, post) {
let result = eval(pre)()
eval(post)(result)
}
}
accountSelector.executeInParallel(processAccountsWithArg('Foo'), 'postProcess');
function processAccount(arg) {
console.log('processAccount', arg)
return JSON.stringify({
key: 'value'
});
}
function processAccountsWithArg(arg) {
return function() {
return processAccount(arg)
}
}
function postProcess(result) {
console.log('postProcess', result)
}

How to extract data from this object?

I am working on some legacy code for my workplace and cannot figure out how to process data from a data object that is returned. The retrieveThis function is supposed to retrieve the object data:
myObj.retrieveThis(new myObj.getThisData({num : 10, page : 1, sorting : "stampDescending"}), function () {myCallback(this);});
var myObj = function () {
var getThisData = {
// this function populates an array and returns it to the retrieveThis function
}
var theObject = {
retrieveThis: function(a, b) {
var OBJ = {};
// OBJ is populated by the data from var getThisData...I checked
setTimeout(function () {
b(OBJ);
}, 1000);
}
}
return theObject;
})();
I am having trouble getting the data ("theObject") to my callback function (or at all). I pass this to myCallback(), where myCallback is:
function myCallback(obj) {
alert(Object.keys(obj));
}
The alert box shows a list of keys including document, jQuery, and myObj. It looks like the data from OBJ is populated from the array allTheData, but I can't seem to pass this back (as return theObject;) to process it. Where am I going wrong here?
Note - I cannot modify this legacy code. I need to process "theObject".
You pass wrong callback function
inside you call it with parameters, so you should define it with parameters
myObj.retrieveThis(
new myObj.getThisData({num : 10, page : 1, sorting : "stampDescending"}),
myCallback);
in this case in first param to myCallback passed OBJ object

TypeError: 'click' called on an object that does not implement interface HTMLElement

I have some javascript that sends data to a function that calls a php page, however I get an error that I can't find any information on. The postData() call is in the middle of another plain javascript function. But I can't get it to submit the data to the php page.
function postData() {
var postdataURL = "path/to/php/page.php";
$.post (
postdataURL, {
"formid":5,
"clientid":1,
"userid":1,
"level":mycat,
"extra":mytimer,
"pid":pid
},
function () {});
}
Review your variable mycat, mytimer, pid is may be a jQuery Object.
That mean you had asigned
mycat = $('#cate')
If that true, you just fix that
mycat = $('#cate').val()
Or some code get real value.
remove the " from the name of the properties
$.post (
postdataURL, {
formid:5,
clientid:1,
userid:1,
level:mycat,
extra:mytimer,
pid:pid
},
function () {});
And add a
alert("Got called");
after
function postData() {
to be sure the function is being called
I ran in to this when doing a jQuery $.ajax() call like you did. Apparently (in my case) it was caused by referencing a variable that wasn't in scope and was undefined. For example, in your code:
"level":mycat,
"extra":mytimer,
"pid":pid
If mycat, mytimer, or pid were null, and you're having the same problem, that would do it.
In my case was the same problem like #user3740976. I put in url an undefined parameter.
$.ajax({
type: requestType,
url: url,
dataType: dataType,
data: dataParams,
...
Where dataParams is
{"title":{},"iSBN":"111","partNumber":"3332","bookCategory":"1"}
title being undefined.

Backbone.js requestPager conditionally exclude paramater from URL

RequestPager sends all the attributes in server_api to the request as query string. However, sometime I want to exclude a parameter on some condition. This is how, i'm setting the param:
server_api: {
query: function () {
return this.searchQuery
},
type: function(){ return this.searchType }
}
If this.searchQuery is empty, it makes the URL like ?query=&type=1. But I don't want to send query or type when it's empty or when my some other condition fails.
I know the dirty way like:
if(!myCollection.searchQuery){
delete(myCollection.server_api.licensed);
}
But this is not maintainable. Because text time I've to create this function. So, I'm looking for a better way of doing this. Any Help?
If you look at how server_api is used:
_.each(_.result(self, "server_api"), function(value, key){
if( _.isFunction(value) ) {
value = _.bind(value, self);
value = value();
}
queryAttributes[key] = value;
});
you'll see that it uses _.result:
result _.result(object, property)
If the value of the named property is a function then invoke it;
otherwise, return it.
var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
That means that you can make server_api a function which returns the appropriate object.

Categories