How to read global variable from WP-Config.php in JS file - javascript

I have defined URL in wp-config file.
DEFINE('URL', 'google.com');
Now i want to access this URL from my JS theme file:
<script> alert(URL); </script>
How to do this?

use localize in functions.php
add_action('wp_enqueue_scripts' , function(){
wp_localize_script('jquery', 'config_var', URL );
});
and in js file => config_var will equal the config variable value

You have to put a bit of your JS in your PHP file (i.e. use script tags to accomplish this). Then do the following:
Place the script in your php file
<script> alert(<?php echo URL ?>); </script>

you can read the php variable inside th js using echo. use like this
var url='<?php echo _URL; ?>';
alert(url);

Related

How to use defined variable(defined in php file) in .js file

I have a config.php file in which I defined a variable SITE(define('SITE',"siteroot") and I have a .js file which included jquery functions. In that file, I have a variable site_root.
Is it possible I can make site_root=<?=SITE?>
I change the .js file to php file and used this code header("Content-type: application/javascript"); to defined the type of the file and include the config file. However, site_root=<?=SITE? return "".
I'm not sure if you have a typo in the question or in the actual code, but
define('SITE',"siteroot");
and
var site_root = "<?= SITE ?>";
// ^ ^ quotes matter
should work fine.
Declare PHP Variable
<?php
$variable = "abc";
?>
<script>
$("document").ready(function(){
var test = "<?php echo $variable; ?>";
alert(test);
});
</script>

Set Javascript Variable From PHP Get Variable

I have a page which I have collected two variables, I want to pass these variables to my document ready function. but for some reason.. My alerts for testing are just outputting the line code rather than the result.
just to note the JS script is in another file which is linked to the page.
PHP
<?php
$cardid = test;
$custid = test;
?>
Javascript
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
});
Put your javascript code into a separate php file under script tag:
<script>
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
})
</script>
Include this file in your main php file (using the include function).
It is not possible to execute php in a separate .js file.
you aren't assigning anything to your PHP variables:
$cardid = test;
$custid = test;
a value which isn't numeric and isn't in between quotation marks is considered a constant in PHP. and the constant test most likely has no value in your PHP environment.
you wanted to assign a string, i guess, so don't forget the quotation marks:
$cardid = "test";
$custid = "test";
Wrong concept.
Your JS is not parsed by PHP, so your approach will not work.
Lets make it work:
You have to give the Variables to JS with one trick: Write it into the HTML in a script-tag, then you can access them in your JS.
Lets assume, you produce a HTML like this in your PHP:
<body>
<div>Hello World</div>
</body>
Now, write the variables for you JS into it, here is a simple approach:
echo "<script>var myVar1='".$_GET['var1']."';</script>\n";
echo "<body>\n";
echo " <div>Hello World</div>\n";
echo "</body>\n";
Okay, very simple, do not do it like this in real, but you got the concept?
So, that was the trick to do this.
P.S. The same way, you get $_POST Data to your JS ;)
Consider using quote to represent string.
<?php
$cardid = 'test';
$custid = 'test';
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script>
$(document).ready(function(){
var custid = '<?php echo($custid); ?>';
var cardid = '<?php echo($cardid); ?>';
alert(custid);
alert(cardid);
});
</script>
PHP code will only be run in files ending with .php. Your.js file is loaded directly and not subject to PHP processing. If you wish to assign values from PHP variables to javascript variables you will need to do so in a script block in your .php file.
For example if you add this to your .php file -
<script type="javascript">
var custid = '<?php echo $custid; ?>';
var cardid = '<?php echo $cardid; ?>';
</script>
Then in your .js file shold look like -
$(document).ready(function(){
alert(custid);
alert(cardid);
});
It is of course possible to run PHP in a .js file. As in the case of running PHP as an Apache module, you can add whatever extensions you want Apache to recognize as PHP scripts, such as:
AddType application/x-httpd-php .php .html .htm .js
starting with php5.3 you could probably get issues so you can try also:
AddHandler application/x-httpd-php7 .php .html .htm .js
AddHandler application/x-httpd-php .php .html .htm .js
AddHandler x-httpd-php .php .html .htm .js
if you still get issues use a 301 redirect or a rewrite rule in your .htaccess, like this for example:
Redirect 301 "^(.*)/dir/example.js$" "http://www.domain.de/dir/example.php" [NC,L,QSA]
if you are on lighttpd go to /etc/lighttpd.conf or on Windoze C:\lighttpd\etc\lighttpd.conf, uncomment the "mod_cgi" line and add this line:
cgi.assign = ( ".js" => "c:/php/php-cgi.exe" )
don't give up just because someone say to you "you can't do this or that" ;-)

$_POST with javascript – it works in javascript but not in jquery plugin

I have a form that gets submitted.
Now I would like to retrieve the submitted data with javascript on the next page.
This works just fine when I put it in the body of the html:
<script>
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
</script>
Now I want to have this functionality in a jQuery plugin method.
I tried the following in my jquery plugin:
$.pluginname.test = function() {
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
};
But when I try to execute it in the body of the html, I get the following error messages:
[Error] SyntaxError: Unexpected token '<'
[Error] TypeError: undefined is not an object (evaluating
'$.pluginname.test')
Why is this code-snipped working in a regular Javascript environment but not when called by a jQuery plugin?
Your PHP tags are being evaluated as JavaScript. That means that PHP is not processing them.
Presumably, this is because you have moved the script to a .js file.
While it is possible to generate a JavaScript file from PHP, that won't help you here: The data you are trying to generate is being submitted to the PHP script that generates your HTML document.
Move the script back between <script> and </script> in the PHP file that generates the HTML.
if this code:
$.pluginname.test = function(){};
is in external js file then you can't assign a php code values to it. It will cause errors. So i have one solution for it like make a args based plugin like:
$.pluginname.test = function(phpObj){
document.write(phpObj["form_input_name"]);
};
and you can call this on your php/html page in the script block like:
<script>
$.selector.test(<?php echo json_encode($_POST); ?>);
</script>
If you want to create a jQuery plugin:
$.fn.pluginname = function() {
var $_POST = 'SOME TEXT HERE';
$(this).text($_POST);
};
$('.el').pluginname();
Demo: http://jsfiddle.net/bfjLo02m/
Note: Make sure jQuery is included before
EDIT:
Since you've placed the plugin in a separate .js file you'll need to pass the PHP variables to your plugin in the index.html file. Here is an example:
// pluginname.jquery.js <-- separate file for your plugin
$.fn.pluginname = function(options) {
$(this).text(options.var1);
};
// index.html (or any html file)
$('.el').pluginname({ var1: $_POST["somePHPVar"], var2: 'var2Value' });

Assigning php variable to javascript alerts PHP source code

I want to assign the php variable $stop to the javascript variable stopped
<?php
$stop = $_POST['stop'];
?>
<script>
var stopped = "<?php echo($stop) ?>";
alert(stopped); //Output: alertbox with the text: <?php echo($stop) ?>
</script>
How can I solve this?
Since the PHP source code is being alerted, the document is not being run through the PHP preprocessor before being delivered to the browser.
Make sure that:
You're using a web server and not loading from a local file
The webserver supports PHP
The file the PHP code is in is one the server expects to find PHP in (typically this will be a file with a .php extension, but it is configurable).

Partial url in CodeIgniter

Fellow Coders,
so far I have been using the CI url helper to build full urls using base_url() and site_url(). Now I'm trying to access a controller function within some javascript code that will be loaded as a js file.
it's actually an ajax call with a url parameter that should be something like:
url : '/account/check_user'
now unless i prefix the url with the full path as ins http://servername/..... the code fails.
all the code examples i've seen use the short version of the url but i cannot get it to work. I'm sure this is really simple but i'm stuck.
i could pass a hidden form field to the js code but i'd rather not. any ideas?
thanks
Well, I also tend to use absolute URLs and a good practice I always do is declaring a JS variable:
var base_url = "<?php echo base_url(); ?>";
In:
the head section
as the first line of my script tag
if I have a main.js file that holds most of my JS code AND it's always included in my views, then I put that line first thing in the file.
After that, you use it like:
url : base_url + 'account/check_user'
Anyway, the first slash / in your url tells the browser to go to the URL root which would not be the right place to put your url chunk in! for example:
if your CI installation is in ci folder and your URL is: domain.com/ci/contorller/method/
Then your URL will become: domain.com/contorller/method/!!
I'm usually assigning the base_url() to a JS variable right in the head to have it available to all methods. Something like this
<script type="text/javascript">
var baseUrl = "<?php echo base_url() ?>";
</script>
You should actually be using CI's site_url() function. base_url() is useful for generating a URL to a resource (such as script or stylesheet), but site_url() is the best choice when generating a URL to a page within the app itself, such as when making an Ajax request, as described.
So the best code to use would be something along these lines:
<script type="text/javascript">
var site_url = "<?php echo site_url() ?>";
</script>

Categories

Resources