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

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

Related

It is necessary in php code where there is a js code to output, for example, through an alert variable [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 2 years ago.
It is necessary in PHP code where there is a js code to output, for example, through an alert variable. Does not work. Please help, tell me how to do it.
And if anyone can how to use this as a URL to the picture
function setLocation($url_image){
$locationName = R::load('locationsdb', $url_image);
echo '<script type="text/javascript">',
'alert("'<?php echo $locationName; ?>'");',
'var img = "<?php echo $locationName ?>";',
'document.getElementById("image_location").src = img;',
'</script>';
}
alert("{"id":"3","location_name":"\u0410\u043b\u0445\u0438\u043c\u0438\u043a\r\n","location_description":"\u0423 \u044d\u0442\u043e\u0433\u043e \u0441\u0442\u0430\u0440\u0446\u0430 \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0435\u0441\u0442\u0438 \u043d\u0430\u0441\u0442\u043e\u0439\u043a\u0438, \u0441\u043f\u043e\u0441\u043e\u0431\u043d\u044b\u0435 \u043f\u0440\u0438\u0434\u0430\u0432\u0430\u0442\u044c \u0441\u0438\u043b \u0433\u0435\u0440\u043e\u044f\u043c, \u0438\u0441\u0446\u0435\u043b\u044f\u0442\u044c \u0438\u0445 \u043f\u043e\u0441\u043b\u0435 \u043e\u0436\u0435\u0441\u0442\u043e\u0447\u0435\u043d\u043d\u044b\u0445 \u0431\u043e\u0435\u0432 \u0438 \u043c\u043d\u043e\u0435 \u0434\u0440\u0443\u0433\u043e\u0435, \u0447\u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0441\u0438\u043b\u044c\u043d\u043e \u043f\u043e\u043c\u043e\u0447\u044c \u0432 \u0442\u044f\u0436\u043a\u043e\u0439 \u0436\u0438\u0437\u043d\u0438 \u0438\u0441\u043a\u0430\u0442\u0435\u043b\u044f \u043f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0439.\r\n","location_travel":"2","location_lut":"-","location_mobs":"-","location_image":"../images/locationsBackgrounds/backgroundAlchemistImage.png","location_runs":"-","location_characters":"-"}");
You can't use <?php tags inside each other. It makes no sense anyway - you're already in the PHP block, you don't need to open it again. And for similar reasons you can't use echo inside another echo command. And again it makes no sense anyway, you're already echoing, so why repeat the same instruction before you've finished the first one?
To generate the text you want, just use string concatenation with the . (dot) operator:
echo '<script type="text/javascript">
alert("'.$locationName.'");
var img = "'.$locationName.'";
document.getElementById("image_location").src = img;
</script>';

How to get code from another file and write everything to one file? [closed]

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 3 years ago.
Improve this question
I need to use htmlspecialchars but it only accepts the address of the file, can I make it accept the code and not the address?
return "<script src='" . htmlspecialchars('static/functions.js', ENT_QUOTES, 'utf-8') . "'" . nonce() . "></script>\n";
function nonce() {
return ' nonce="' . get_nonce() . '"';
}
function get_nonce() {
static $nonce;
if (!$nonce) {
$nonce = base64_encode(rand_string());
}
return $nonce;
}
The HTML <script src= is going to fetch a resource and run it, from wherever you have specified in the src attribute. It's expecting a URL.
The htmlspecialchars( function is expecting a string, and will return a string.
The way you have it right now, it will take the string "static/functions.js" and process it.
Your question suggests you want it to operate on the contenst of the file. This is techncially possible, but the file has to be fetched first.
htmlspecialchars( file_get_contents(__DIR__ . 'static/functions.js') )
But that still seems odd. You want to convert all the encoded special characters in your JavaScript file to their HTML entities? Like < to <? That's almost surely going to make the JavaScript invalid.
Even if it didn't ruin your JavaScript, you'd still be trying to take the contents of that file and putting them in the src property of the script tag, which is expecting a URL.
Overall this seems like you need to step back and think about what exactly you're trying to accomplish.
Edit for OP question in comments
<div>
<span>Some regular HTML content</span>
</div>
<script>
<?php
// we're now in PHP, about to store some JavaScript as a string
$js = <<<EOD
console.log("I am a JavaScript console message!");
console.log("Me too!");
EOD; // note this can't be indentend or spaced, it has to be flush left
// we can 'echo' the JavaScript directly into the HTML
echo $js;
?>
</script>

Embedding JavaScript in PHP [closed]

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.

Struggling to use PHP inside JavaScript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
In one PHP file I have a variable named $difficulty.
I need to access this file in my javascript file, game.js.
I have tried this inside my game.js file:
userDif = "<?php echo json_encode($difficulty); ?>";
console.log("Difficulty " + userDif);
However, this does not work, it just prints out "<?php echo json_encode($difficulty); ?>"
I have also tried just:
userDif = <?php echo json_encode($difficulty); ?>;
But then you get an error as it doesn't expect "<"
Any help would be greatly appreciated.
Edit: Apologies: This has already been answered! I was just searching for the wrong thing. Sorry!
Don't put quotes around the value. json_encode() will put quotes around the string, so you end up with extra quotes. It should be:
userDif = <?php echo json_encode($difficulty); ?>;
I think you have something like this:
Php file
Js file included in php file
You have to run js code with php inside the php file, then you can use that variable inside the js file.
Php file:
<script type="text/javascript">
var phpCode = "<?php echo 'hola'; ?>";
</script>
<script src="scriptFile.js" type="text/javascript"></script>
scriptFile.js:
alert(phpCode);

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

Categories

Resources