I have tried to combine php variables in javascript, I have read in many forums that it is complicated to do the combination of both but it is possible (according to the answers). My problem lies in the following:
In my php code I have a variable called $images of type string which I would like to be able to use in javascript, for example:
<?php
$imagenes = "imagen1.pngimagen2.pngimagen3.png";
?>
<script type="text/javascript">
var img = <?php echo $imagenes;?>
</script>
I don't know if something like the code I entered can be done, any suggestions?
Greetings and thanks.
Effectively. Passing the value of variables from
PHP
ajavascript
is trivial (note the value, not the references ;-). As you have also been told. You have to keep in mind that if it is the string type you must do it in the following way:If by chance you want to pass the value of type
array
... which I guess because the value of$imagenes
... doesn't make much sense to me, you should do it in the following way:And if you want to pass a
array
fromPHP
to aarray
fromjavascript
:There are many ways to do the job, but in all cases you have to be especially careful with escaping quotes. Without that, unwanted effects could occur in the application.
We could use
addslashes()
to do the job:This method would not be completely secure because discrepancies in the character set (do not use
utf-8
) could allow the closing of the tag</script>
, causing security problems ( XSS ).To improve security and to support arbitrary data (classes, arrays, etc) it is better to use
json_encode()
:If
$prueba
it is a character string, itjson_encode
will quote its content and will escape any quotes inside it. If it's an array it will use[]
, or use{}
for classes/objects etc.TL;DR (too long, you don't need to read it)
If you could have problems or discrepancies in the character encoding (the one returned by the server headers does not match the one indicated in the HTML or you simply do not use
utf-8
) I recommend adding the a parameterJSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS
injson_encode
the following way:The safety of the function
json_encode()
is more than enough if everything is properly coded inutf-8
. The RFC indicates that by default it is usedUTF-8
although it couldUTF-16
also be used , so if different character encodings are mixed, a quote for a certain character set could be incorrectly escaped.Of course you can send information from
PHP
toJavascript
without problems. In fact, the way you do it is correct because itPHP
is a server-side language andJavascript
a client-side language, you will not have any problems because all the codePHP
is executed before theJavascript
.In fact it is quite common to combine
PHP
withJavascript/jQuery
and is not seen as a bad practice.It is very easy to achieve
as you can see there is no complication it is the same as using them in html using
echo