Access MyBB PHP variable with Javascript - javascript

Is it possible to grab a MyBB PHP variable with Javascript? I am an userscript coder, and right now I use:
var uid = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
To grab the user id (uid) of the current user. However, if I were to grab the UID from the user with PHP, it would look like this:
<?php echo {$mybb->user['uid']} ?>
Now to the actual question. Is it possible to grab the UID through Javascript, using the $mybb->user['uid']?

My answer is Yes, you can but it has some limits.
Well, if you remember in every headerinclude templates always have these code:
<script type="text/javascript">
<!--
var cookieDomain = "{$mybb->settings['cookiedomain']}";
var cookiePath = "{$mybb->settings['cookiepath']}";
var cookiePrefix = "{$mybb->settings['cookieprefix']}";
var deleteevent_confirm = "{$lang->deleteevent_confirm}";
var removeattach_confirm = "{$lang->removeattach_confirm}";
var loading_text = '{$lang->ajax_loading}';
var saving_changes = '{$lang->saving_changes}';
var use_xmlhttprequest = "{$mybb->settings['use_xmlhttprequest']}";
var my_post_key = "{$mybb->post_code}";
var imagepath = "{$theme['imgdir']}";
// -->
</script>
You can use MyBB's variables in any template with one condition: it's must be defined in the correlative PHP file. (Of course that variable must be inside the brackets { })
For example, the correlative PHP file with headerinclude template is global.php.
That's it. Have fun with MyBB :)

You can add a plugin to your forum. It is called template conditionals. Once you have that installed you can use the Mybb->user variable in all templates. There are many applications of this plugin, but for your code you can do:
<setvar uservar>$mybb->user['uid']</setvar>
var {$tplvars['uservar']} = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
The plugin is on the MyBBHacks forum at the link below.
http://mybbhacks.zingaburga.com/showthread.php?tid=464

First, you will not be able to directly access a php server side variable in javascript, but there are several work arounds you could do.
The first one that comes to mind is to put this in your html page somewhere
<script type="text/javascript">
<?php echo "var uid = '". $mybb->user['uid']."';" ?>;
</script>
The downside to this is that this variable is now directly view able and editable in the DOM.

If you are using (or can use) a template you may place a PHP variable in a JavaScript variable defined within that template's content. If you plan to run this JavaScript on every page you must add the variable definition to the script block in the headerinclude template.
<script type="text/javascript">
<!--
var userID = {$mybb->user['uid']};
// -->
</script>
That example script will place the user's uid in the JavaScript variable userID.
Please note that <?php echo $mybb->user['uid']; ?> will not work as MyBB's template system does not allow PHP tags within it. You may instead use {$mybb->user['uid'} as an alternative.
Also, take note that if you are using a plugin and eval'ing the template in a function in your plugin file you will also need to globalise the PHP variable you are going to use.

Related

I want to display a php code shortcode in JavaScript, how do I do that?

This is my code
enter image description here
<script>
let myDiv = document.createElement("div");
myDiv.classList.add('test');
let my_var = `<?php echo do_shortcode("[elementor-template id="5078"]"); ?>`;
myDiv.innerHTML = my_var;
document.querySelector("#instagram").appendChild(myDiv);
</script>
Actually, it is not possible to do it this way because the script is being fired on the client-side while the PHP interpreter is working on the server-side.
If you are sure that you need to use JS to render some PHP code, I'd suggest sending a request using wp_ajax https://codex.wordpress.org/AJAX_in_Plugins to send a request on a server, and then the server can return any PHP code result that you want. Don't forget that shortcodes may use additional assets that will not be sent as a response.
The best way is to use shortcodes in a native form inside the content or PHP templates. Especially the elementor template where you can create template parts for different places of the website easily.
It's an enclosure problem:
You used nested double quotes in your php – resulting in breaking the echo.
Provided, your <script> tag is in your template php (so your php shortcode could be parsed) try this (replace the shortcode double quotes by single quotes):
<script>
let myDiv = document.createElement("div");
myDiv.classList.add('test');
let my_var = `<?php echo do_shortcode("[elementor-template id='5078']"); ?>`;
myDiv.innerHTML = my_var;
document.querySelector("#instagram").appendChild(myDiv);
</script>

How can I pass smarty variable to .js file for var definition?

I have in php getting id from server request for parameter id
$id = $_REQUEST['id'];
$smarty->assign('id', $id);
And in the smarty .tpl display files {$id} outputs the number to the client browser.
I need this variable in the javascript for the page:
var id = {$id};
I use id later in the javascript to define datatables default search value.
"oSearch": {"sSearch": offer_id},
My problem is I need to properly pass the id to the javascript, if is set at all. Right now it displays {$id}. Any ideas, please?
In your template (.tpl) file, include the code
<script>
var id = {$id};
console.log(id); // for debugging purposes
</script>
In your browser's Javascript console, you should be able to see the value of id.

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

Pre-set javascript variables from URL parameters

Imagine I have a script abc.js, which has one global variable userid. Several AJAX requests are made instantly after it is loaded (it can happen after or before DOM is parsed by browser). I need the script to have different variable value for different users. Requests has to be made instantaneously after JS is available. Here is what I am looking for:
Browser makes a request to /js/abc.js?userid=12345
Server parses userid=12345 and adds userid = 12345 to the script
Server returns the script to user
Browser parses the script and userid is set to 12345, then everything is processed normally.
Is there a way to do this with some Apache/Lighttpd extension? Since I can't rely on <script>userid=12345</script> at the begining of the document, as abc.js will most probably be executed before userid=12345 is evaluated.
You can simply use PHP to output the javascript variables at a point before when the abc.js script is called. In this case the parameter would be passed to the main PHP script (i.e the page). Like this:
<script type="text/javascript">
var userid = <?php echo $_GET['userid']; ?>;
</script>
<script type="text/javascript" src="/js/abc.js">
Of course you probably want to sanitize the parameter value in PHP before using it.
Here, abc.js can just reference the value of userid in global scope. There is no need to pass userid to the script in URL and have Apache use PHP to dynamically generate the js file. In fact, you likely don't want that approach as it prevents optimal browser caching of the script.
If you don't want PHP involved you have other options to pass this data such as the URI parsing option presented by #yent, HTML5 localStorage, cookies, etc.
You can parse window.location.search and set window properties :
var p = window.location.search.substr(1).split(/&/);
if(p.length && p[0]) for(var i=0; i<p.length; i++) {
var a = p[i].split(/=/);
window[a[0]] = a[1];
}

Using JavaScript Variables On Different Files

I have a js variable defined in a js file like so :
onlineUsers.js :
var _onlineUsers=new Array();
I'm then linking the js file into index.html like so
<script type="text/javascript" src="onlineUsersVars.js"></script>
and I know for sure it gets a value after awhile since I've checked it with alert .
However , when I try to do the same with another html file , e.g file2.html
then link the js file to get the same variable
file2.html :
<script type="text/javascript" src="onlineUsersVars.js"></script>
and check the value , the value is nothing .
Anyone has a clue what I'm missing ? Do javascript variables 'die' after being linked to one page ? How can I share the same global javascript variable between many html pages ?
You will have to include the script (onlineUsers.js) on every HTML page. And the variable (_onlineUsers) will need to be re-instantiated on every HTML page.
Yeah if you go from file1.html to file2.html, even though you have the same JS file on both files, the values will all clear. The best way to pass variables from page to page would be by using cookies.
Try using HTML5 localStorage to store the variable and then call it each time you need to.
function onlineUsers() {
var _onlineUsers=new Array();
localStorage.onlineUsers = _onlineUsers;
}
Then this value will be available anytime you need it. Although that is client side not server side.

Categories

Resources