I want to define functions and scripts in a database record then using Javascript convert the database field from a string to code.
I was thinking I could use 'eval', but this doesn't seem to work.
As an example:
var strTest = "function(strParams) { alert('hello: ' + strParams); };"
,fn = eval(strTest);
fn("World");
This doesn't work, eval returns undefined, hopefully this gives the idea of what I am trying to achieve.
The problem is that eval parses your function as a function declaration. But function declarations require a name.
Instead, you should make it a function expression, which doesn't require one.
var strTest = "(function(strParams) { alert('hello: ' + strParams); })";
eval(strTest)("World");
Only do this if you trust the string.
Alternatively, you may be interested in the Function constructor:
var f = Function("strParams", "alert('hello: ' + strParams)");
f("World");
You could try something like this:
<script src="http://my-server/js-func/foobar.js"></script>
and have the server serve up the JS retrieved from the DB at that endpoint.
Related
I've added a field to our wordpress backend where I can write text into it.
(for example "colorVariation + btnVariation) -> That should define a specifc order for the js variables later
I'm able to receive this text in my js file with the wp_localize_script function.
wp_localize_script('wc-product-js', 'script_vars', array(
'order' => get_field("wc_variation_order"),
)
);
It seems to be, that this variable get's converted into a string when I try to use the variable in my js file. like that:
var colorVariation = '_red';
var btnVariation = '_male';
var order = script_vars.order;
var varId = '.variation' + order;
My expected output would be ".variation_red_male" but the output is ".variationcolorVariation + btnVariation)
Is there any way to convert this string?
Alright. Finally I've found the function by myself. It's eval().
The eval() function is able to evaluate or executes an argument that
is passed inside it. If the argument is an expression, this function
will evaluate the expression and the argument is one or more
JavaScript statements, eval() executes the statements.
Quote from https://www.codespeedy.com/convert-string-into-variable-name-in-javascript/
var colorVariation = '_red';
var btnVariation = '_male';
var order = script_vars.order;
var varId = '.variation' + eval(order);
I have a general problem with JavaScript. I am trying to construct long argument used in function in my project via separate method. In the end I am able to produce a String with necessary arguments, however I cannot insert it into the method as parametres. When I do, I get different errors from the API I am using. Problem is, that there are several parametres in the method and when I insert the method generating said arguments, the method treats those arguments only as a long String. I've tried using eval() and String() methods, however without success.
I know that those generated arguments are correct, because when I use console and do everything step by step, I can generate those arguments and then manually copy them in the method, which works.
Could anyone tell my how to force the browser to treat inserted String as a "code already written in method"?
Thanks and sorry for not including the code, I cannot show it to anyone yet.
Edit:
The code looks similar to this:
function buildArguments(args) {
var title='Something';
var interval=1;
var type='Something';
var build = '{title: {text: "' + title + '"},' +
'axis: { interval: ' + interval + '}, ' +
'dataType: { type: "' + type '"}};'
return build;}
function graph(args) {
var graph = new MyGraphAPI.Create(buildArguments(args));
graph.chart();}
and it should create something like this:
var graph = new MyGraphAPI.Create(
{
title: {text: "Something"},
axis: {interval: 1},
dataType: {type: "Something"};
}
);
It's possible there are some mistakes, I've written the code in haste only as an example. However you should get the idea.
Edit2: I should also add that those arguments in build function are used in creating the final string of arguments in final method (even though I didn't include this in the example).
You need to convert the string to object. Something like:
callfunc(eval("{a:1,b:2}"));//equals callfunc({a:1,b:2})
If you want to pass multiple arguments, and they are into an array, you can do:
callfunc(...["arg1","arg2"]); //equals callfunc("arg1","arg2");
Both together:
callfunc(...eval("['arg1',{someobjval:1,someabjvaltwo:2}]"));
However this is bad style. Why do you need a string? Can't you just build an object/Array?
I am coding in node.js atm. I need to create a dynamic variable and invoke it.
e.g.:
username = 'im_a_user';
global['ws[' + username + ']'] = ws; //(yes, i want to store the connection with ws module)
but
ws[im_a_user].send('blabla');
doesn't work and node shuts down. So I want to know how global['ws[' + username + ']'] looks like for debbuging.
Do you know how I can print it - or even better, why im_a_user in ws[im_a_user].send('blabla'); isn't defined?
Thanks for your time!
Accessing object property is possible with brackets, but you have to give it a valid expression: a string literal or a variable. Looks like you are referencing a variable that is not defined. That's where Node chokes.
So try either with a variable that is defined
var key = 'im_a_user'
ws[key].send('blabla');
or a string literal
ws['im_a_user'].send('blabla');
I have one c# web application in which put one link dynamically like,
if (oObj.aData[1] == '2') {
Id = oObj.aData[7];
Name = oObj.aData[2];
alert(Name);
return ' Show ';
//this is
}
function like,
function Show(id,name)
{
alert('calling');
}
but my function not calling.
Is any syntax error or anything else which I forgetting?
Please help.
You need to pass Name in quotes(''), with in quotes to be treated as string parameter. Otherwise they will be treated as JS variable which obviously you have not defined, You must be getting error 'example string' is not defined. in browser console.
return ' Show ';
Note: If Id is a string, also pass it in quotes('')
This may be of some help.
Starting from Firefox 34 and Chrome 41 you will be able to use an ECMAScript 6 feature called Template Strings and use this syntax:
String text ${expression}
Example:
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
source: JavaScript Variable inside string without concatenation - like PHP
How can I convert a string in javascript/jquery to a function?
I am trying to use a JSON parameter list to initialize a function. However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.
For example, if my JSON is:
json = { "one": 700, "two": "function(e){alert(e);}" }
Then in my code:
parameters = eval(json);
$('myDiv').addThisFeature({
parameter_1: json.one,
parameter_2: eval(json.two) // <= generates error
})
Example: http://jsfiddle.net/patrick_dw/vs83H/
var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
var parameters = JSON.parse( json );
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"
You'll need to load the JSON library in browsers that don't support it.
Or do two separate evals:
Example: http://jsfiddle.net/patrick_dw/vs83H/1/
var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
eval( 'var parameters = ' + json );
eval( 'var func = ' + parameters.two );
func( 'test' );
I assume you're aware of the dangers of eval.
Looking for a way to not use eval this is the best I could come up with. Use the Function constructor to create a function from a string.
var parsed = JSON.parse('{"one":"700", "two":"function(){return 0;}" }');
var func = new Function('return ' + parsed.two)(); // return parsed.two function
alert(typeof func); // function
alert(func()) // 0
Use this:
parameters = eval('(' + json + ')');
$('#myDiv').addThisFeature({
parameter_1: parameters.one,
parameter_2: eval('(' + parameters.two + ')') // <= does not generate an error
});
Adding the parentheses at the beginning and end of the string prevents the syntax error.
Note, however, that you are parsing JSON using eval (which in some cases has security risks, but I assume that is irrelevant because you do want to run arbitrary code sent by the server). If you have the server-side flexibility (to send invalid JSON), you could just send the function not quoted as a string and eval should be able to parse that just fine.
See this SO question. As was said, JSON is meant to hold data. To treat a piece of the data as a function, you would first need to eval the string.
You are eval'ing an anonymous function, which of course won't be called by anything. If you really wanted to run the code in the json then the text would need to be alert(e).
However it doesn't sound like a very sensible thing to do. You'd be better off writing code to deal with the contents of the json object, rather than trying to run code embedded in the json.
Neither way is particularly nice, but if you can get rid of the function(e) wrapper bits, then you can use var myDynamicFunction = new Function("e", "alert(e);"); Otherwise, you're looking at using eval(). Eval() is evil in general. If this is JSON that you're getting back from a $.getJSON call or something, you're opening yourself up to security concerns.