Use PHP to pass values to JavaScript [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
How to read an array in PHP inside JavaScript? Like this
<?php
$f(0)=69;
$f(1)=8;
$f(2)=25;
$f(3)=5;
$f(4)=32;
?>
<script>
var barChartData = {labels : ["Ene","Feb","Mar","Abr","May","Jun","Jul"],
datasets : [
{
fillColor : "#e64608", strokeColor : "#e64608",
data:[65,59,90,81,56,55,40]
},
{
fillColor : "#acadb1", strokeColor : "#acadb1", data :
[28,48,40,19,96,27,100]
}
]
}
var myLine = new
Chart(document.getElementById("bar").getContext("2d")).
Bar(barChartData);
</script>
I would like to replace the "data" in the data with the ones in the PHP array.

The best solution id to load data using ajax. Another option is to render data as follows.
<script>
var barChartData = <?php json_encode($array); ?>
</script>

Related

How can I insert php while code into javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
Hello there im learning php also javascript but i dont know how to put a while loop into javascript parameters area.
<script type="text/javascript" src="//....." async="true"></script>
<script type="text/javascript">
window.criteo_q = window.criteo_q || [];
var deviceType = /iPad/.test(navigator.userAgent) ? "t" : /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Silk/.test(navigator.userAgent) ? "m" : "d";
window.criteo_q.push(
{ event: "setAccount", account: 62056}, // You should never update this line
{ event: "setEmail", email: "##Email Address of user##" }, // Can be an empty string
{ event: "setSiteType", type: deviceType},
{ event: "viewItem", item: "##HERE##" });
</script>
And the goal is output of "##HERE##" needs to be done php while loop from database. (I can give detailed description if asked)
If the file is .php exentension, you could have a <?php echo "JAVASCRIPT CODE" ?> with that you can could an output javascript inputing variables into it, by using concatenating. It is not a good pratice, but would soulve your problem.

How can i use php variable from js? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
I have several products. On click product, I send "id" of clicked product to Local Storage. To use this variable in php I send it to items.php ($.post).
Then I need use this "id" from items.php to show in the cart, but variable is emply.
var LSArray = JSON.parse(localStorage.getItem('productID')) || [];
function clickOnProduct(id) {
var newItem = {'id': id};
LSArray.push(newItem);
localStorage.setItem("productID", JSON.stringify(LSArray));
var dataLS = JSON.parse(localStorage.getItem('productID')) ;
$.ajax({
type : "POST",
url : "/wp-content/themes/twentynineteen/items.php",
data : { name : dataLS[dataLS.length-1].id },
success: function(res){
console.log(res);
}
});
}
All works fine, but how can I use "id"?
<?php incude(items.php); ?>
dosn't work.
You are sending it by post. So you can take a look to your post variable by
<?php var_dump($_POST); ?>
Then you will see the array and probably you can access your data by
$_POST['name']

How I can use the Javascript variable in PHP? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have that code:
function saveData(position, map) {
var latlng = marker.getPosition();
var late = latlng.lat();
var longe = latlng.lng();
<?php
require("sql.php");
session_start();
$name = 'prova';
$address = 'temare';
$type = 'bar';
$late = "<script>document.getElementByID('late').value</script>";
$longe ="<script>document.getElementByID('longe').value</script>";
I need to get late and longe variables in PHP but this doesn't work, anyone knows how I can do it?
You can't access javascript variables using PHP as JavaScript is executed on client side ( browser ) and PHP on server side.
The best what you can do is send data from those variables as request to server and read them, for example using jQuery ajax request:
Good example you can find here:
jQuery Ajax POST example with PHP
Or you can use this:
javascript
function sendData(variable1, variable2) {
$.ajax({
type: 'post',
url: 'myphpscript.php'
data: 'var1='+variable1+'&var2='+variable2
});
myphpscript.php
<?php
$variable1 = $_POST['var1'];
$variable2 = $_POST['var2'];
<script type="text/javascript">
<?php $abc = "<script>document.write(late)</script>"?>
<?php $def = "<script>document.write(longe)</script>"?>
</script>

Why this is variable does not work? Jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am writing the following code below, which basically takes the data from the current date to a PHP file to handle in jQuery. Until here everything well. But I'm not understand why I can not have a new value of the total variable after it picks the value coming PHP file.
day.each(function () {
var $this = $(this);
var the_index = $this.index();
var the_date = $this.find('h3.date').html().substr(0,2);
var the_day = $this.find('h3.day');
/*THIS VARIABLE*/
var total = 0;
$.get('trd/datetime.php', function (date) {
if(that.hasClass('list-'+date.day)) {
weekList.find('.item.list-'+date.day).addClass('active');
}
total = date.firstDate;
}, 'json');
console.log(total);
});
I don't know if my english helps, but, please, tell me what wrong I'm doing!
Thanks.
The .get call is asynchronous -- the stuff inside it runs after your console.log statement.
You probably want to use a callback, which you invoke from inside the .get handler:
$.get('trd/datetime.php', function (date) {
// ...
callback(total);
}, 'json');
function callback(total) {
console.log(total);
}

Need to pass a value from PHP to Javascript [duplicate]

This question already has answers here:
how to pass these strings from php to javascript
(5 answers)
Closed 9 years ago.
I need to pass a value from PHP back to my javascript. I have tried so many things but can't get it to work. Here is my code.
<script type="text/javascript">
life = {};
life.anjaxEnter = function(finished) {
$.ajax({
dataType:"json",
type:"POST",
data:mydata,
url:"myurl.php",
async:false,
success:life.receiveResult,
});
setTimeout("location.href='myredirectionurl'", 1000); // Redirect after 1 second
}
life.receiveResult = function(result) {
alert(result);
}
</script>
I need to pass a specific value from the PHP file back to life.receiveResult and then add this to the redirection url.
The biggest problem is probably that at the time when you assign life.receiveResult to success, life.receiveResult is undefined. You need to define it before you assign it to something else.
myurl.php needs to return a JSON result when it's called. Something like this:
<?php
header("Content-Type: text/json");
$mydata = "Hello";
echo json_encode(array('ok' => true, 'mydata' => $mydata));
?>
Have a look at the json_encode docs, the header docs and some of the other answers for more information.

Categories