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>';
Related
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>
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.
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
Inside profuser variable i have string "nick".
echo a href="#" onclick="prof('.$profuser.')">
#UP I DELETED THE SIGN BEFORE a BECOUSE IT WAS DESTROYING WHOLE CODE IN STACK OVERFLOW
It should be sent here:
<script>
function prof(profuser){
var xmlhttp=new
window.XMLHttpRequest(); xmlhttp.open("GET", "user.php?user=" +
profuser, true); xmlhttp.send(); }
</script>
And then to this file called user.php:
$thisuser = $_GET['user']; echo $thisuser;
But this code shows me that string "nick" is not defined.
Could anyone tell me what is wrong about it please?
And if there are more errors in this code tell me please.
As error say nick is treated as undefined variable. It should be seen as string so you need to add quotes:
onclick="prof(\'' . addslashes($profuser) . '\')"
According to #p.s.w.g, you should use addslashes() to escape quotes from php variable in case there were any;)
try this.
onclick="prof('<?php echo $profuser; ?>')"
or
onclick="prof('<?= $profuser; ?>')"
I think you are mixing PHP and javascript? Hard to tell from the limited code that was posted.
Your issue is most likely a quoting one, if you are printing the whole onclick bit try this
echo 'onclick="prof(\''.$profuser.'\')"';
This is because you are probably getting something like this in your source.
onclick="prof(nick)";
And nick is a string not a javascript variable, which will be undefined.
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
This question may have already been answered, but how can I import variables from PHP into a segment of Javascript in HTML? I have the following PHP variables (these are parameters passed into a PHP script):
$user = $GET[user];
$pass = $GET[pass];
And I am trying to access these variables with the following references in my Javascript code:
var user = "<?=$user?>";
var pass = "<?=$pass?>";
However, when I check the values of these variables with console.log I get the following result:
user =
pass =
Where am I slipping up? It seems like I just can't read these variables from PHP.
Multiple bugs:
$user = $_GET['user'];
^----^----^--- missing
var user = "<?=$user?>";
^^^^^^^^^^---nasty and can break JS.
Never dump arbitrary text from PHP into a JS code block. One single JS metacharacter and you've introduced a syntax error and the entire JS block is killed. Always use json_encode():
var user = <?= json_encode($user) ?>;
Change:
$user = $GET[user];
$pass = $GET[pass];
To:
$user = $_GET['user'];
$pass = $_GET['password'];
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>';