Embedding JavaScript in PHP [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would just like to get a simple explanation as how embedding javascript in php works and why we need to echo it out. I just need to understand the concept of embedding javascript to php. I may just have been confusing myself but I just need someone to shed some light on this topic.

It's like any other programming language - you can use only THAT particular programming language to accomplish something. e.g.
<?php
$x = 42; // php variable assignment
alert($x); // javascript function call
This would never work. `alert() is a JS function which (usually) has no analog in PHP, therefore this would die with an undefined function error.
Since PHP can be embedded in other languages, and other languages can be "embedded" within PHP, you HAVE to have clear delimiters between the two, so the compilers can tell where one language ends and another starts. With php, that'd be accomplished by doing an "echo" of the JS code, or "breaking out" of PHP mode:
<?php
$x = 42;
?>
alert(<?php echo $x; ?>);
or
<?php
$x = 42;
echo 'alert(' . $x . ')';
What it boils down to is "context". If you're in PHP mode (e.g. within a <?php ... ?> block, you're writing PHP code, and any other language you use in there (html, JS) is just plain text as far as PHP is concerned.
If you're "out" of PHP mode, then you're in whatever language context the surrounding block is using.
<script>
var x = 42;
<?php // some php code here that causes output />
</script>
In the above case, your "context" is javascript - anything that the PHP causes to be output must be valid in the Javascript context it's embedded in.
so while
var x = <?php echo 42; ?>;
would work, because 42 is a valid bit of text to have in that particular spot, it would not be valid to have
var x = <?php echo '</script>'; ?>;
That would produce the non-sensical
var x = </script>;

JavaScript is client side, PHP is server side... Javascript can not be accessed by PHP.. You must use something like AJAX to pass back and fourth.. On the flip side, you can display PHP inside JavaScript.
<?
$a = "25";
?>
<script>
alert(<? echo $a ?>)
</script>
That works, but visa versa will not unless you use Ajax.

You should make all justifiable attempts to separate languages whenever possible.
Just the same as any other data PHP parses it will only output what you tell it to. So if you don't tell PHP to send the data to the browser it wont send it.
With regard to language separation there are loads of PHP template engines out there that work out of the box to do this for you. You just need to work within their framework.

Related

Passing hostname from PHP to Javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
For marketing reasons, I want to personalize my website based on what ISP/service provider someone is using. Google Analytics/Optimize/GTM do not provide this out of box. ISP/host lookup can be done with PHP, but I need the value in javascript so I can push it to the data layer.
I am not a developer, I've been piecing together bits and pieces from PHP references, Javascript references, and Ajax references.
This is what I have in my (WordPress) header file before closes. My website doesn't crash when it loads, but the javascript variable is constantly empty.
What can I do to pass it as a javascript variable?
<?php $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']); ?>
<script>var jsHostname = <?php $hostname?>;</script>
You dont need php to get the hostname ,With only javascript you can get the hostname, using the following:
var host = location.hostname
json_encode() deals with arrays, strings etc.
<?php echo $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']); ?>
<script> var jsHostname =<?php echo json_encode($hostname); ?>;</script>

Echo PHP Code in Javascript [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I would like to echo some php code in javascript for certain reasons but the code does not get executed, when i use the code inspector i notice that the php code has been commented out.
This is the code:
var code = '<?php echo time_passed(strtotime(' + new Date().toLocaleString() + ')); ?>';
$('#page').html(code);
basically i am passing the javascript datetime value to a php function which should then echo the results into the code variable.
I then output the value of code to a container with an id of page.
PHP is on the server end. In the manner your using, there is no way to for PHP and JavaScript code execution to interact. You would need to user AJAX to communicate between front end execution (JavaScript) and back end execution (PHP).

use Js Variable in php [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
i want to use javascript varible in php..i refered much stackoverflow link and google but i didn't get proper solution..i also know js is client side scripting language and php is serverside..but i want js varible in php and i had also try with ajax call but i want set time zone in this file not other file so ajax call is not working in my situation.any one help me how to get same result for varible in echo and var_dump...
<html>
<script type='text/javascript'>
var timezone = jstz.determine();
var timezone=timezone.name();
console.log(timezone);
// it print 'Asia/Kolkata';
<?php $abc = "<script type='text/javascript'>document.write(timezone)</script>"?>
</script>
<?php
echo $abc;
// it print 'Asia/Kolkata';
var_dump($abc);
// it print string '<script type='text/javascript'>document.write(timezone)</script>' (length=65)
?>
</html>
any help must be appreciated..Thnks
you can use php variables to javascript but not javascript variables to php.. because javascript executes on client side and php executes on server side.. so php is executed before javascript gets executed..
So simply you cant...
the only thing you can do this by using ajax....

accessing a PHP variable in javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In my controller, I'm passing the image which is an array in this way:
$this->load->model('site_model');
$data['images'] = $this->site_model->fetch_images();
$data['main_content'] = 'my_view';
$this->load->view('includes/template', $data);
Everything up to know is perfect and even I can have the following in my view which shows the path of the first element:
echo $images[0]['path'];
But in view in script I'm trying to do the following which gives me Uncaught SyntaxError: Unexpected token ILLEGAL"
alert('<?PHP echo $images[0]['path']; ?>');
Why is that? Is not that possible?
Thanks
The path you're outputting contains backslashes, which in JavaScript strings begin an "escape sequence" -- basically a typable representation of a character that otherwise you'd have trouble putting into a string. But when they appear naked in a string, JS often chokes on them.
Rather than echoing the path directly, try this:
alert(<?= json_encode($images[0]['path']) ?>);
That will make PHP format the text in a way that'll cause fewer problems in JS.
(In some versions and configurations of PHP, <?= might not work. You can use <?php echo in its place; it does the same thing. It's just wordier. :P )
Try this
alert("<?php echo $images[0]['path'] ?>");
or try putting you php variable into a Javascript variable
to do so simply:
var data = "<?php echo $images[0]['path'] ?>";
alert(data);
cheers!
Try to JavaScript alert this way to store into $path variable,
$path = echo $images[0]['path'];
Now you print this $path into alert box
echo '<script type="text/javascript"> alert("' . $path . '");</script>';

Unable to pass php variable as parameter to javascript function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The case is that I have a .php file and inside it, I have a function inside script tags. After it, I have php code, that reads from a file. I want to sent the file data to the js function. I had done this before, but now it will produce parsing errors.
SOLUTION
THE file format must not have line breaks!!!!
echo '<script>updateMatch1("'.$filetext.'") </script>';
Here is the code
<script>
function updateMatch1(names) {
alert(names);
};
</script>
<?php
/* Read file */
...
$filetext = fread( $file, $filesize ); //checked the output, it's ok
// numerous ways I tried. Some produce an error and the page isn't loaded at all,
// while others produce an error in the console
echo "<script>updateMatch1('" . $filetext . "');</script>";
//echo '<script> updateMatch1($filetext);</script>';
//echo '<script>updateMatch1();</script>';
//echo "<script>updateMatch1($filetext" . ")</script>";
//echo "<script>updateMatch1($filetext)</script>";
//echo '<script>updateMatch1(' . $filetext . ');</script>';
?>
Check your file.txt. Maybe it contains some illegal character or has some incompatible file encoding that produce the illegal character. If you print the value of $filetext with php, there is no visible error, but it can produce some in JS. E.g. it can be the zero-width space.
See if you have spaces or other characters on the end of the file.
If you did not hide anything from your code, then this dots are producing parse error
/* Read file */
...
You should get rid of ...
Also, have in mind that:
<?php $filetext = "alalala"; ?>
<script>
updateMatch1('<?=$filetext;?>');
</script>
Will produce the correct alert 'alalala', but:
<?php $filetext = "alal'ala"; ?>
<script>
updateMatch1('<?=$filetext;?>');
</script>
will produce:
SyntaxError: missing ) after argument list
updateMatch1('alal'ala');
Escape your file output before pass to js.
You can try a simple escape:
<?php $filetext = "alal'ala"; ?>
<script>
updateMatch1('<?= htmlspecialchars($filetext, ENT_QUOTES);?>');
</script>
There are lots of dupicate questions on stackoverflow dont ask everything just search bro!!!
For samples:
how to pass php parameter to javascript
How to pass JavaScript variables to PHP?
Passing parameters to Javascript using PHP
Answer was given by #iMx!!
The reason was that the .txt file contained line breaks. These would break the syntax.
The solution was to separate the names by whitespaces, instead of newlines, and everything was ok!
echo '<script>updateMatch1("'.$filetext.'") </script>';

Categories

Resources