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!
Related
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.
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.
I need to grab the value of URL after #. For example in this URL: http://url.com/index.php#33/1032. I just need to get "33/1032" But PHP seems to not allow any value after #. So I used JS. Here is how I am doing it.
<script>
function curState(){
var state = window.location.hash.substr(1);
return document.write(state);
}
</script>
Now that I have the url I need to pass this portion of the URL 33/1032 back again to the url after POST call. Here is how I am trying to do:
<?php
$copyVal = " <script> curState(); </script> ";
echo $copyVal; // displays value in browser perfectly
?>
Now,
<form action="index.php#<?php echo $copyVal ?>" method = "post" >
// form code
</form>
After submit it displays
http://url.com/index.php# <script> curState(); </script>
But I want
http://url.com/index.php#33/1032
Please help.
Thank You.
Use jQuery -
<form action="index.php" method = "post" id="myform" >
The jQuery will be -
var state = window.location.hash.substr(1);
$('#myform').attr('action', $('#myform').attr('action') + '#' + state);
FIDDLE
Instead of PHP code, use JavaScript:
copyVal = curState();
copyVal = "index.php#"+copyVal;
function for_action()
{
document.getElementById('myForm').action = copyVal;
}
Now, In form tag:
<form id="myForm" onsubmit="for_action();" method = "post" >
First figure out your problem:
PHP is a server side scripting language. Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.
So codes under <?php tag will run first in server side and give output as HTML and/or JavaScript and/or CSS respectively. So
<?php
$copyVal = " <script> curState(); </script> ";
echo $copyVal; // displays value in browser perfectly
?>
this code will run in the server and first assign <script> curState(); </script> as a string in php variable $copyVal. And secondly, when you echo $copyVal, this will output <script> curState(); </script> in your source code.
AS <script> curState(); </script>
is a Javascript code as well so curState(); function call your javscript function you have define earlier. On that function you have used document.write to write something in your browser, so you see the output in your browser. But if you see the source code of your page, you can still see that there is no specific Hash value but a JavaScript code [<script> curState(); </script>].
As similar as that when you print your php variable $copyVal in
<form action="index.php#<?php echo $copyVal; ?>" method = "post" >
this variable output the JavaScript code rather than any hash value.
Second, How to do this?
You can do this in many way with php or JavaScript. If you want to do this with php, one simple way is that, first parse_url your current url. and than get the fragment value. like-
$url=parse_url("http://url.com/index.php#33/1032");
echo $url["fragment"]; //This variable contains the fragment
If you are not sure, how to grab the current url in php see Get the full URL in PHP
you can take the link and use the function substr..it does what you want after a specific sign:
$id = substr($url, strrpos($url, '#') + 1);
this should do the job
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.
I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.