Add a php created array into javascript - javascript

I am using a javascript slide show on my index page. Instead of the array being static, I want to build the array with PHP and add it with something like and include statement. Since the array is inside the javascript I am unsure how best to do this. Here is a sample of the array:
var fadeimages=new Array()
fadeimages[0]=["pics/fade_pic_1.jpg", "", ""]
fadeimages[1]=["pics/fade_pic_2.jpg", "", ""]
fadeimages[2]=["pics/fade_pic_3.jpg", "", ""]
And here is the PHP file that builds the array. It works great. I just don't know how to place it in the javascript code:
<?php // Build fadepic array for index page
$x=0;
foreach (glob("pics/*.*") as $filename) {
$filename = substr($filename, 20); //gets just the file name
echo "fadeimages[".$x."]=[\"pics/".$filename."\", \"\", \"\"]<br>";
$x++;
} ?>
Thank you in advance for any help you can give me!

You can use json_encode() for this.
<?php
//buildfadepic.php
$result = array();
foreach (glob("pics/*.*") as $filename) {
$result[] = array("pics/".$filename, "", "");
}
print json_encode($result);
This will give you valid JSON (and hence valid JavaScript). If you want to mix JavaScript and PHP, you should be able to do it like this now
var fadeimages = <?php include "buidfadepic.php"; ?>;
Since buidfadepic.php will give you a result like this
[ ["pics/foo.jpg", "", ""], ["pics/bar.png", "", ""], ...]
Or if you have both in the same file, simply print/echo instead of include as suggested in the comments.

The right way, as the comments said would be using json_encode.
For example:
Server
<?php
$files = array('file1.jpg', 'file2.jpg', 'file3.jpg');
$view->assing_var('files', $files); // if you're separating the view from the php, else just do return for including
View (client):
<script type="text/javascript">
var images = <?=json_encode($files)?>;
</script>

I agree with other posters that JSON would be a nice clean way to do this. But you don't necessarily have to, you can also include the array straight away:
<script type="text/javascript">
var fadeimages=new Array();
<?php
echo "fadeimages[0] = ...;"; // Include code to create array
?>
</script>
Just to clarify (based on the comments we seem to have a bit of misunderstanding): you can put PHP code inside <script> tags. After all, the PHP code is run server-side and the client that runs the JavaScript will also see the resulting output. So as long as your PHP script does not produce syntax errors in the JavaScript you should be OK.
An alternative approach, if the script becomes very large, is to include your PHP script as an external JavaScript:
<script type="text/javascript" src="list_fade_images.php"></script>

Related

Lost formatting for a price when bypassing jQuery

I am trying to modify a Monero payment gateway extension for Wordpress/WooCommerce so that it prints some basic payment information as normal HTML, beyond just rendering it with jQuery. It is important that this code works Javascript free. I have modified the template where this information displays so that there are <noscript> elements which contain the following...
<?php echo $details['amount_total_formatted']; ?>
That is an example of one element but there are a few others in the template. The issue is when I test this the output is formatted incorrectly.
The output appears like this 714229029442 and not as 0.714229029442 like when Javascript renders the output.
Here is a snippet of this array being created in the method which includes the template I am modifying...
$details = array(
...
'amount_total' => $amount_total,
'amount_total_formatted' => self::format_monero($amount_total),
...
);
Here is the body of the format_monero method and the defines it uses...
define('MONERO_GATEWAY_ATOMIC_UNITS', 12);
define('MONERO_GATEWAY_ATOMIC_UNITS_POW', pow(10, MONERO_GATEWAY_ATOMIC_UNITS));
define('MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF', '%.'.MONERO_GATEWAY_ATOMIC_UNITS.'f');
public static function format_monero($atomic_units) {
return sprintf(MONERO_GATEWAY_ATOMIC_UNITS_SPRINTF, $atomic_units / MONERO_GATEWAY_ATOMIC_UNITS_POW);
}
The template file I am working on has the below JS code which assigns variables within using JSON and also gives it AJAX support. It does$details_json = json_encode($details) before including the JS.
<script type="text/javascript">
var monero_show_qr = <?php echo $show_qr ? 'true' : 'false'; ?>;
var monero_ajax_url = '<?php echo $ajax_url; ?>';
var monero_explorer_url = '<?php echo MONERO_GATEWAY_EXPLORER_URL; ?>';
var monero_details = <?php echo $details_json; ?>;
</script>
When using the Javascript and using the developer tools there is a variable called amount_total_formatted defined within which is formatted properly with the decimal place.
I want to format the XMR price in my PHP within the template with the proper formatting including the decimal place, and I want to keep changes to the template that do it as simple as possible. I admit I do not really understand the format_monero method used to do some kind of formatting or what jQuery does once being passed that value.

Create JavaScript Array From MSSQL Query

I am attempting to create a JavaScript array from a MSSQL query results. Below is my syntax that I attempt to use, but the array is not created. How should this be set-up so that the JavaScript array is properly assigned?
<?php
$mssql = new mssql("localhost", "user", "password", "testdb");
$data=mssql_query($mssql,"SELECT * FROM test");
?>
<script>
var firstNames=[<?php
while($info=mssql_fetch_array($data))
echo $info['f_name'].',';
?>];
<?php
$data=mssql_query($mssql,"SELECT * FROM test");
?>
var lastNames=[<?php
while($info=myssql_fetch_array($data))
echo '"'.$info['l_name'].'",';
?>];
</script>
<?php
$mysqli->close();
?>
A good approach here would be to get the query (after correcting the deficiencies in the code as noted below your post, then casting the whole array to JSON using json_encode($data); and then echo $data in to your javascript.
This is not the only way to do it. I'm sure others will suggest other things.
Look at this page: https://www.w3schools.com/jquery/ajax_ajax.asp
I know, W3 Schools isn't the best, but it's okay.
You can do that with jQuery easy, just google a bit and you need php knowledge for creating an array out of a mysql query.

PHP Preg_Match_All Returning No Results

I am using Simple HTML Dom Parser to scrape a script tag from a webpage and then attempting to parse certain data from said tag using preg_match_all(). However, when I print preg_match_all, no results are returned.
Below is the code I'm using:
<head>
<?php
require_once "toolkit/http.php";
require_once "toolkit/web_browser.php";
require_once "toolkit/simple_html_dom.php";
?>
</head>
<body>
<?php
$prod_url = 'http://www.domain.com/subpage.html';
$html = file_get_html($prod_url);
$script = $html->find('script', 17);
//echo $script;
preg_match_all('(?<=\d":)\w++', $script, $matches);
print_r($matches);
?>
</body>
I can see that the HTML Simple Dom code is working correctly, as I get the results I expect when echoing the $script variable. The results are:
<script type="text/javascript">
var PRODUCT_JSON = {
"Def":{
"default":202705111,
"Listing:[{
"label":"Includes",
"options":[
{label:"All", id: "884"},
{label:"None", id: "485"},
]
}],
"Lookup":{
"1":202705111,
"0":202493236
}
}
};
</script>
So, the issue appears to be with the regex I'm using in preg_match_all(). The goal of the regex is to return the two numbers, 202705 and 202493, near the end of the script tag. It may have to do with escaping the double quote or parentheses, though I've also tried preg_match_all('\(?<=\d\":\)\w++', $script, $matches); with the same result. Any ideas on what I'm doing wrong?
If you keep forgetting about delimiters, you can use T-Regx, which automatically adds delimiters.
$matches = pattern('(?<=\d":)\w++')->match($script)->all();

Is it possible to use the same variable in two different javascript blocks?

I am developing a web that has to show an sql view, so I did the query with PHP, but I have to show the result in charts, and I am trying to use the google geochart. So basically what I want to do is:
Select the data from an SQL view with PHP.
Get the data from PHP into a javascript variable so I can use it in the chart.
Get the value of the javascript variable to put in the google chart api, so it show what I want.
So far, I've got the point 1 and the point 2 (I think) done. But when I am trying to use the javascript variable again in another part of the code it has no value, so no data is showing, I am getting undefinedon the explorer.
Relevant Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?php
//connections and stuff
$tsql="SELECT count(*) as Qty, ShipCountry FROM [Orders Qry] group by ShipCountry"; // yes, is the Northwind database example
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query table: ".$tsql);
}
else
{
$json=array();
$i=0;
echo "<script type='text/javascript'> var countries = []; </script>";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";
$i=$i+1;
}
//echo "<h1>". $json["ShipCountry"] ."</h1>"; //I was testing, so the problem is not in retrieving the data from the database.
sqlsrv_free_stmt($stmt);
}
?>
<p>
<script type="text/javascript">
document.write(countries[0]);
</script>
</p>
</body>
</html>
You forgot to quote $row['ShipCountry'] (seems to be a string);
echo "<script> countries[".$i."]= '". $row['ShipCountry'] ."';</script>";
Note the new quotes.
You might want to consider using AJAX to query a different file from within your javascript, cf. http://www.w3schools.com/ajax/ajax_php.asp.
If you have your PHP file return JSON to the AJAX request, javascript will have an object that it understands and you can use it there. This way you can have all your javascript in one place. E.g. this pseudo code:
Javascript.js
function gimmeACountry(i){
var countries = AJAX.get('countries.php');
return countries[i];
}
PHP.php
<?php
$result = mysql_stuff(...);
print json_encode(result);
?>
HTML
<html>
<head>
<script src='Javascript.js'>
</head>
<body onload="document.write(gimmeACountry(0));">
</body>
</html>
If you really want to use just one file, a few thoughts:
You don't need to open and close a statement every time you write javascript. All of your PHP could be embedded in one.
You can output most of your javascript outside of the block, instead of echoing everything. I think the PHP is clearer then. E.G.
<script>
<?php $foo = 'bar'; ?>
var foo = <?php echo $foo ?>;
document.write(foo); // writes 'bar'
</script>
If you are still have scope issues, you can try adding your variable to the window object, e.g.
window.countries = []
This might be problematic if you end up doing more stuff with javascript later. I really do recommend you use AJAX.
You should use push method and Array() Construct
var countries = [];//nope
var countries = new Array();//yep
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";//nope
echo "<script> countries.push(".$row['ShipCountry'].");</script>";//yep
push method documentation
Distributing javascript over two blocks works fine:
<html xmlns="http://www.w3.org/1999/xhtml">
<head />
<body>
<script>
countries = ['foo'];
</script>
<script type="text/javascript">
document.write(countries[0]);
</script>
</body>
</html>
But the problem is that your PHP isn't generating valid java script. Have a look at your browser's JS console, and you'll see ReferenceErrors because you didn't quote the country names.

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

Categories