Set Javascript Variable From PHP Get Variable - javascript

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" ;-)

Related

Jquery if/else statement with dependencies on php session variable [duplicate]

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>
In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');
PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not
Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>
Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.
alert("Delete entry <? echo $row['id']; ?> ")
If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

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

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);

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>

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).

pass parameters using variable?

This is a simple syntax question.
I declare a variable:
<script type="text/javascript">
var id_1= '<?php echo $id; ?>';
</script>
And then in a externally loaded js file im trying to call a function using the variable (the external js file is loaded after the ^^ variable declaration:
loadComments(id_1);
The id_1 is being passed literally as 'id_1', not recognizing it should be a variable. What am I doing wrong?
var id_1 = '<?php echo $id; ?>';
Will echo something like this:
var id_1 = '10';
Which is treated as a string in JavaScript. You want to do this instead, so that you assign a number to id_1:
var id_1 = <?php echo $id; ?>;
This will print out something like this:
var id_1 = 10;
The php code is recognized only by a .php file.
Put your code in a .php file and run it on you local server

Categories

Resources