PHP loop values into javascript array - javascript

Hello I built a manual slider using jquery, and I put my images' location inside an array, but now I want to load images from the database, and I want to loop them to a javascript array. How can this accomplished?
<?php
$get = $connect->query("SELECT imagem FROM slider ORDER by id");
while($fetch = $get->fetch_array(MYSQLI_ASSOC)){
}
?>
<script>
var items = ["url(images/banner_1.jpg)","blue","black","green"];
</script>

Here is a simple/low-frills method. It doesn't have any external dependencies as you mentioned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Use PHP in JavaScript</title>
</head>
<body>
<?php
// assuming your database call returns a valid array like this
$things = array("banner_1.jpg", "banner_2.jpg", "banner_3.jpg", "banner_4.jpg");
// the built-in `json_encode` will make JavaScript like it
$things_json = json_encode($things);
?>
<div class="etc">
<!--this is were the database items will go-->
<ul id="things"></ul>
</div>
<script>
// echo out json-ified PHP directly into the script tag
var things = <?php echo $things_json ?>;
// loop through the json and append list items to our target element
for(var i = 0; i < things.length; i++) {
document.querySelector('body').innerHTML += '<li>' + things[i] + '</li>';
}
</script>
</body>
</html>
The main tricks here are:
use json_encode($your_array_here), which is built in to php
echo the json directly into a script tag in the body.
You can even work with the new things variable from an external script assuming you keep it in the global scope and have your external js run on DOMContentLoaded or similar.
Here are some images of the code working:
Note that json_encode() will only accept one variable at a time. If you need to pass multiple variables down into the script, you can build up an array (map) in php with array functions, or just json_encode() each variable separately and make multiple echo calls inside the script tag.
<?php
// assuming your database call returns a valid array like this
$things = array("banner_1.jpg", "banner_2.jpg", "banner_3.jpg", "banner_4.jpg");
$more_things = array("banner_5.jpg", "banner_6.jpg");
$both_things = array_merge($things, $more_things);
$both_things_json = json_encode($both_things);
?>
<script>
// echo out json-ified PHP directly into the script tag
var bothThings = <?php echo $both_things_json ?>;
</script>

A much simpler method, without adding things in the DOM, and since you asked for a javascript array:
You have to always remember that PHP executes first in server and javascript later in the browser. So you can use your php to create (valid) javascript, like this:
<?php
echo '<script>var jsArray = [];';
while($fetch = $get->fetch_array(MYSQLI_ASSOC)){ // I took your line exactly as you wrote it
echo 'jsArray.push("'. $fetch['field'] .'");'; //you change 'field' with whatever you need
}
echo '</script>';
?>
The output of php script (the code that will be executed by javascript) will be something like this:
<script>
var jsArray = [];
jsArray.push("blue");
jsArray.push("red");
jsArray.push("yellow");
</script>
After that, you will be able to access jsArray.

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.

How to give PHP variable to Javascript?

I am searching for a better way to send my PHP variable to Javascript. Currently I echo the variable in PHP:
<script>
var numbers = <?php echo $numbers ?>;
</script>
I then access this variable in Javascript like this: class.method(numbers);
My PHP file is included in the index.php before the javascript file, so I have access to this variable in the javascript file.
Now I am looking for a nicer way to submit the PHP variable than using echo. Does anyone have an idea?
The output of numbers looks like:
If you want to mix your php with JS .the one you have used is better .also you can try something like this
Add a display none span to your html page with id :document_target
example
<span id="document_target" style="display: none;"><?=$numbers;?></span>
in js file get data of span with id
var myNumber = document.getElementById("document_target").textContent;
Here is a possible way to do this:
Get the values from the form fields if there's a form, or whatever and send them in a query to php from JS, this work regardless where the php file is, it can be a remote file on a different server, or just another local page,etc.
The php file receives the request and reply back
retrieve the reply of the php file in the JS.
An example of the above using jquery:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
$(document).ready(function(){
$("#submit_button").change(function(){
var my_id = "some value here, or do some getelement by id .val()..."
$.ajax({
url: 'includes/forms.php', //or replace with a remote url
method: 'post',
data: { some_requestPHP_name: my_id } //note this line
}).done(function(data){
console.log(`js got from php =${data}` )
//
var numbers = data;
})
})
})
Now in the php file you need to make the file react whenever it recieves something containing the line I indicated above containing some_requestPHP_name, this is a parameter that you decide
if (isset($_POST["some_requestPHP_name"])) echo some_function(); // you can use the "some_requestPHP_name" just as a trigger to call the some_function of you can use the data from it
function some_function(){
// do things and return the number;
return 1;
}
Depending on your usage you may not have a form/button etc so you may want to remove the .change() and execute the function right away, at this point it's up to you to adapt the example to your needs.
You can use an inline script tag to add data to the HTML document like this:
const dataElement = document.querySelector('#phpData'),
data = JSON.parse(dataElement.text);
console.log(data.example, data.number);
<!-- This tag is what really is rendered on the page -->
<script type="text/plain" id="phpData">
{
"example": "Example string",
"number": 10
}
</script>
<!-- This tag is written in the source code of the page -->
<script type="text/plain" id="phpData">
{
"someValue": <?=$some_value?>,
"otherValue": <?=$other_value?>
}
</script>
As can be seen, when running the example, the script with inappropriate JS type attribute is not executed.
In that script tag you can echo variables or other values as you need (like in the latter example), or even echo a json_encoded string. This is one of the safest way to include PHP variables to JS, and you can still save your actual JavaScript into an external file. The data script must be included in the HTML document, because you can't access .js files with PHP, and also, for security reasons, JS can't read text from an external file.
What comes to the usage of echo, it's a PHP language construct specifically meant to add content to the markup, there's no reason to avoid it. I've used a short hand of echo in the latter example, but it still is echo.
One better alternative would be to output the PHP value to a data attribute. Given that this variable doesn't seem to be tied to a specific element, you could put it at root level on the body element. Then you can read it from there when the JS executes once the DOM has loaded, like this:
<body data-numbers="<?php echo $numbers ?>">
<!-- your HTML ... -->
</body>
let numbers = document.body.dataset.numbers; // plain JS
let numbers = $('body').data('numbers'); // jQuery
This is under the assumption that the $numbers variable in your PHP is holding a value which can be coerced to a string
-- Update --
Given the edit to your question where you clarify that $numbers in fact contains an object, you can instead encode it to JSON, output it to a <script> tag and then use it from there:
<script type="text/plain" id="numbers">
<?= $json_encode($numbers) ?>
</script>
let numbers = JSON.parse(document.querySelector('#numbers').textContent.trim()); // plain JS
let numbers = JSON.parse($('#numbers').text().trim()); // jQuery
Well, I did it like this:
<script src="./assets/scripts/tableActions.js"></script> <!-- JS SCRIPT -->
<table class="w-full" id="table">
<thead>
<tr><th class='border-b p-2 w-52 border-gray-400'>Full Name</th><th class='border-b border-l p-2 w-52 border-gray-400'>Username</th><th class='p-2 border-l border-b w-36 border-gray-400'>Role</th><th class='p-2 border-l border-b border-gray-400'>E-mail</th></tr>
</thead>
<tbody>
<?php
include('./functions/connectSQL.php');
$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);
$x = 1;
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr class='hover:bg-gray-800 cursor-pointer' onClick='returnValues(".$x.");' id='tableRow'><td class='border-t p-2 px-4 border-gray-400' id='fullnameCell'>" .$row["fullname"] . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='usernameCell'>".$row["username"]."</td><td class='border-l border-t p-2 px-4 border-gray-400' id='roleCell'>" . $row["role"] . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='emailCell'>" . $row["email"] . "</td></tr>";
$x++;
}
mysqli_close($con);
?>
</tbody>
</table>
See, that onClick='returnValues(".$x.");' have inside itself variable from PHP. So you will give varibale to javascript using function. Now it is like you probably know:
function returnValues(x){
const table = document.querySelector('table');
const cells = table.querySelectorAll('td');
const values = Array.from(cells).map(cell => cell.innerText);
var tableRow = document.getElementById("table").rows;
var form = document.getElementById("form");
const usernameField = document.getElementById('usernameForm');
for (i = 0; i < tableRow.length; i++){
let tableCells = tableRow[x].cells[i].innerHTML;
form.elements[i].value = tableCells;
}
if(values.includes(usernameField.innerText)){
formButtonAdmin.innerText = "Update";
}
}
Now you could be good, when you will have any other questions, feel free to ask :D
Have a nice day!

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.

Pass Data To a Javascript File [duplicate]

How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

PHP function return value to JavaScript

I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.

Categories