How to read the information in configuration files(.properties) in JavaScript? - javascript

In my code, I need to get data from configuration file(.properties) .My configuration file looks something like this(.properties):
maxTime = 60
upVotePostMaxTime=60
but I don't know how to read the configuration file in JavaScript. Is there a better way of doing this?

It is not advisable to read configuration files from JavaScript. Instead you could do this:
Read the file on server-side (using PHP, .Net or Python or any other language that you prefer)
Render the valid values to JavaScript. Something like:
var maxTime = "<?php echo maxTime; ?>";
var upVotePostMaxTime = "<?php echo upVotePostMaxTime; ?>";
where <?php echo maxTime; ?> and <?php echo upVotePostMaxTime; ?> will have values 60 each.
This would show on the client-side as:
var maxTime = "60";
var upVotePostMaxTime = "60";
and then you may use it in JavaScript.
Values are assigned in double quotes to prevent breaking of JavaScript code in case null values are sent from the server.
Please ensure that proper values are assigned to JavaScript variables.

Related

Lost formatting for a price when bypassing jQuery

I am trying to modify a Monero payment gateway extension for Wordpress/WooCommerce so that it prints some basic payment information as normal HTML, beyond just rendering it with jQuery. It is important that this code works Javascript free. I have modified the template where this information displays so that there are <noscript> elements which contain the following...
<?php echo $details['amount_total_formatted']; ?>
That is an example of one element but there are a few others in the template. The issue is when I test this the output is formatted incorrectly.
The output appears like this 714229029442 and not as 0.714229029442 like when Javascript renders the output.
Here is a snippet of this array being created in the method which includes the template I am modifying...
$details = array(
...
'amount_total' => $amount_total,
'amount_total_formatted' => self::format_monero($amount_total),
...
);
Here is the body of the format_monero method and the defines it uses...
define('MONERO_GATEWAY_ATOMIC_UNITS', 12);
define('MONERO_GATEWAY_ATOMIC_UNITS_POW', pow(10, MONERO_GATEWAY_ATOMIC_UNITS));
define('MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF', '%.'.MONERO_GATEWAY_ATOMIC_UNITS.'f');
public static function format_monero($atomic_units) {
return sprintf(MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF, $atomic_units / MONERO_GATEWAY_ATOMIC_UNITS_POW);
}
The template file I am working on has the below JS code which assigns variables within using JSON and also gives it AJAX support. It does$details_json = json_encode($details) before including the JS.
<script type="text/javascript">
var monero_show_qr = <?php echo $show_qr ? 'true' : 'false'; ?>;
var monero_ajax_url = '<?php echo $ajax_url; ?>';
var monero_explorer_url = '<?php echo MONERO_GATEWAY_EXPLORER_URL; ?>';
var monero_details = <?php echo $details_json; ?>;
</script>
When using the Javascript and using the developer tools there is a variable called amount_total_formatted defined within which is formatted properly with the decimal place.
I want to format the XMR price in my PHP within the template with the proper formatting including the decimal place, and I want to keep changes to the template that do it as simple as possible. I admit I do not really understand the format_monero method used to do some kind of formatting or what jQuery does once being passed that value.

How to write get text in grid.js using php tag

I want to write get-text for language conversion with the help of php tag.
I try to use gettext php tag in grid.js but it's not working for language translation.
I have try this code for use gettext in generate_grid.js
Code:
word_hello = "<?php echo gettext("hello"); ?>"
alert(word_hello);
Using this code grid loading stopped so how I can use get text in jquery.
Using gettext flexigrid load without any error.
We have tried to another solution like call javascript function to header.php file like below.
word_hello = header_fcuntion('hello');
alert(word_hello);
In header.php we do like this.
function header_fcuntion(txt){
var new_txt = "<?php echo gettext('"+txt+"'); ?>";
alert(new_txt);//Response in English Language hello
}
But we try like put static hello that time it alert in converted language in header.php file.
function header_fcuntion(txt){
var new_txt = "<?php echo gettext('hello'); ?>";
alert(new_txt);//Response in Convert Language hello
}
So is there anything wrong to call function in php file?

pass PHP Variable to JS

The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....

Passing PHP integer to JavaScript

I have been reading so many posts and none of them seem to work for me I have no idea what I am doing wrong. I want to call a PHP integer in JavaScript and set it to a JavaScript variable so I am then able to use that variable in my calculations.
average = '<?php echo $average; ?>';
console.log("value" + " " + average);
This is the code I have been using and it prints to the console:
value <?php echo $average; ?>
This is clearly not the resulted I wanted, I wanted it to print the integer.
My $average PHP integer is also located in a different file so I used:
<?php include 'DBObject.php';?>
I want to be able to do a calculation like:
drone1percentage = 1000 / average * 100;
but since the average variable isn't taking the php integer $average from my other file it doesn't work.
You could add this to your .htaccess, so PHP will interpret js files too.
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Or rename that .js to .php and add this header in front of the file:
header('Content-Type: application/javascript');
You "cannot" execute php inside a javascript file.
However there are some tricks to get to your variables from php.
One of them is creating a javascript variable with php and use this variable inside your javascript file.
Example:
// Inside your php file
<script>
var average = <?php echo $average; ?>
</script>
<script src="yourjavascriptfile.js"></script>
// Inside your javascript file
console.log(average);
use jQuery.ajax - http://api.jquery.com/jquery.ajax/
var average;
$(function(){
$.get("path/to/script", function(data, status){
average = data;
});
});
For me the most reliable way to get information from PHP into javaScript is using jQuerys ajax functionality.
So if you have something like
yourPHPFile.php
<?php
if($_POST['action'] == 'getAverage') {
echo returnAverage();
die;
}
function returnAverage() {
//your average calculation here
return $average
}
You could do something like
yourJavaScriptFile.js
var average = null;
$.ajax({
method: 'POST',
url: '/path/to/yourPHPFile.php',
data: {action: 'getAverage'},
success: function(response) {
average = response;
}
});
Just put this inside a function that is triggered whenever you need it.
For this to work you need to have jQuery included. For further information about the jQuery.ajax() functionality see The Documentation.
Please also note that some ajax parameters might differ depending on the version of jQuery you use.
Your js file has to end in .php for example example.js.php in order for the php code to be parsed.
While you cannot put php code into a .js file, you can create a js file from php
You could also setup the web server to parse all .js files as php code, but that would be a bit too much perhaps.
Try this:
average = parseInt('<?php echo $average; ?>');

Pass Data To a Javascript File [duplicate]

How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

Categories