I have a javascript function receiving php arrays like this :
let options = <?php echo $arrayoptions; ?>;
let optlibs = <?php echo $arrayoptlib; ?>;
let forms = <?php echo $arrayforms; ?>;
It works well but problem arises when I try to minify function. All minifiers I tried gave en error with php part. What can I do ?
Yes, you will run into errors because PHP is not part of Javascript syntax.
Even your Javascript part for the arrays seems dynamically generated by PHP.
This will be impossible to handle.
The only way to work around this would be modify your javascript to fetch those arrays and store them somewhere your whole script can access them for later use.
Then, the script can be minified without issue since PHP syntax are no longer part of it.
Related
I'm working on using React (javascript) inside a WordPress plugin but my plugin requires some data retrieved from the database. I could probably retrieve the required data in javascript using jquery or an API call, but since the data will be static, it seemed more efficient to embed the data using php prior to rendering the DOM element with javascript.
I tried the following, but the <script> tag containing the json never appears in the DOM.
<?php
$events = \Civi\Api4\Event::get()
->addSelect('*')
->addOrderBy('start_date', 'ASC')
->setLimit(25)
->execute();
echo "<script type=\"application/json\" id=\"eventList\">";
echo json_encode($events);
echo "</script>";
?>
<div id="civi-react-events">
<h2>Loading...</h2>
</div>
Update
It turns out the code above works. It turned out to be a cache issue. Ctrl-Refresh is your friend.
Thank you to those who took the time to respond.
Sometimes, json_encode returns tags, texts, etc. with a wrong format. It may lead to break the script tag To ensure the json is fine to use, use the json_encode flags. I personally recommend using the following flags:
<?php
$jsonExportConst = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;
$eventsJson = json_encode($events, $jsonExportConsts);
echo "<script type=\"application/json\" id=\"eventList\">{$eventsJson}</script>"
I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Executing PHP code inside a .js file
(5 answers)
Closed 2 years ago.
I am trying to fetch data from php, store it as json and load it into my javascript code.
I stored my variable in php like this:
$data = array[];
$data = json_encode($raw_data);
Now I want to retrieve that data and use it in my javascript file.
I tried to use the following code in my js file:
var data ="<?php echo $data ?>";
[screenshot]: https://i.stack.imgur.com/pDfsf.png
If the data is only needed once on page load, you can use a script bloc inside the PHP code and then use a JS function to fetch it. But if data is being updated according to the user's interaction with the page, keep in mind that you can't send data from server side in PHP to the client side in JS without using AJAX.
I suggest you read about and use one of these 3 methods:
XHR
fetch
or axios
You are declaring the string to the variable data by using quotes.
Please remove the quotes and that would behave as per your expectations.
So your code should be replaced by the below lines.
var data =<?php echo $data ?>;
var data = <?php echo $data ?>;
or
var data = JSON.parse("<?php echo $data ?>");
The most obvious problem is your quote marks, which make the variable a string in JavaScript, rather than a complex object with a data structure. So any references to properties etc in the variable would not work. The quote marks should be removed so that the data is rendered as an object literal into the emitted JavaScript.
But there's another signficant issue: if this is being done in a .js file as you state, then the PHP interpreter is not running there, so the echo won't work (quotes or no quotes), because it isn't executed by PHP and turned into data. You'd just see the PHP code directly embedded in the JS code.
You'd have to echo the data into a script block in the .php file, then call the appropriate function in your .js file and pass the data as a parameter. This will work nicely if the data is only needed once.
e.g.
PHP file
<?php
$data = array[];
$data = json_encode($raw_data);
?>
<script src="someJsFile.js"></script>
<script>
var data = <?php echo $data ?>; //inject the data into the JS as an object literal
someFunc(data); //pass the data to a function in someJsFile.js
</script>
JS file:
function someFunc(data) {
//your code to process the data
}
If you need to keep it updated during the lifetime of the page, then you'll need AJAX to be able to request new data from the server, as suggested in one of the other answers.
Can somebody please explain to me where can PHP script get this functions from, I have a PHP script that has this few lines:
<?php
$args1 = array();
$gethosts = get_xml_host_objects($args1); //grabbing internal xml data from backend
$args2 = array();
$gethoststatus = get_xml_host_status($args2);
$args3 = array();
$getparenthosts = get_xml_host_parents($args3);
So I do not understand from where and how could this PHP script be referencing those functions, could somebody just give me few examples suggestions of where to look?
Maybe, there is a file that includes the two scripts. Somethings like that
<?php
include 'file_with_function.php';
include 'your_file.php';
?>
These lines can help. Place them at the beginning of your file
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
It looks like those were self defined functions, maybe you can try grep thru entire source tree to see if which .php file define these functions and include it in this script.
Hi have looking on various questions but none of them seem to help me. I have a php variable in my php code and I am trying to access that in my javascript when I do. . .
var thing = "<?php echo($phpvariable); ?>";
then when I do
alert(thing);
It comes out to be "<?php echo($phpvariable); ?>" in the alert statement
What am I doing wrong?
Your PHP is obviously not being parsed. Are you in a .php file? If you're in a .js file, you'll need the server to parse those (or, more safely, put the PHP part somewhere in the DOM that the JS can access)
However, you're doing it wrong:
var thing = <?php echo json_encode($phpvariable); ?>;
Note: no quotes. json_encode will take care of that for you.
If this code is in a function in javascirpt that executes on click or at a specific event, then:
You are writing PHP Syntax in javascript, there is no way that you load the page then you run the php code. PHP code runs on the server side, so before any other HTML Javascript code executes
Else if you want to dynamically set the variable thing in javascript when the page is first loaded, then most probably you meant to write in the php file:
var thing = <?php echo '"'.$phpvariable.'"'; ?>;