This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I'm having problems with the following loop, which generates null results for the variable newLat[i]. However, when I directly populate newLat[0] (in the last 2 lines) it works fine. Any thoughts?
PHP:
$sql = "SELECT `id`, `name`, `lat`, `lng` FROM `markers` " ;
$result = $dbc->query($sql);
$hits = $result->num_rows ;
echo "<br /> Records = " ;
echo "$hits <br />";
while($row = $result->fetch_assoc()) {
$MarkerID[] = $row['id'];
$MarkerName[] = $row['name'];
$MarkerLat[] = $row['lat'];
$MarkerLng[] = $row['lng'];
}
and Javascript:
var myhits = <?php echo json_encode($hits); ?>;
var newLat = new Array (myhits);
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
newLat[0] = <?php echo json_encode($MarkerLat[0]); ?>;
document.write (newLat[0]);
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
You're trying to include PHP code in your JavaScript loop. This is simply impossible, as all PHP is evaluated on the server, while JS is on the client. Open your webpage and "view source" -- you'll see there probably isn't anything on that line.
You'll have to figure out another way to do this; perhaps send $MarkerLat to the client the same way you do hits.
You can't use a FOR pointer inside a different language block:
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
You are trying to use a JavaScript i inside a PHP block. Not only has the PHP block executed by this point, it wouldn't know what to do with that i. It will be 0.
You need to dump the contents of $MarkerLat[i] into a JavaScript array before running it through your loop.
Related
I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
I have the following code which returns the result I require inside of a tab. But because the JavaScript is in the same file it shows a blank tab when there is no data to show. I remove the JavaScript and the tab disappears. How can I run the JavaScript only if data is present so the tab will disappear? Or can I call it from another file?
<?php echo $block->escapeHtml($block->getProduct()->getData($this->getCode()));
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
Since you have to hide the tab if escapeHtml() returns empty value. So you can create a condition block to add the script if escapeHtml() returns a non-empty value.
<?php $EH = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if ($EH) {
echo $EH;
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
<?php } ?>
My knowledge on PHP is not the best, so I will just describe it like that.
Just save the data in a variable
If the data exists (e.g. is not empty)
Print data and JavaScript code
If it does not exist, do nothing
Here is some pseudo-code:
<?php
data = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if (data exists) {
echo data;
echo /* Your JavaScript Code*/;
}
?>
Use a if statement that within the php tags that check value id present then you can render the the java script tags as well as the value.
<?php
$val = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
$script = '<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>';
if($val != "" || $val !=null)
{
echo $val;
echo $script;
}
?>
I am trying to make an application in which I use the simple while loop in PHP file to show the record. the code in product.php is here: How to use this in javascript. I need to call the in the java file in the same way.
$sql2 = "SELECT * FROM product";
$result2 = $DBcon->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$pname = $row2["product_name"];
$timg = $row2["thumb_img"];
$pimg = $row2["product_img"];
if(!empty($timg)){
echo '<img src="adminpanel/upload/product/'.$timg.'" alt="'.$pname.'" title="'.$pname.'">';
}else{
echo '<img src="adminpanel/upload/product/'.$pimg.'" alt="'.$pname.'" title="'.$pname.'">';
}
}
}
If you need to call something in javascript from php in the same file you could do something like this
var h=<?php $h ?>;
This question already has answers here:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?> [duplicate]
(6 answers)
Access PHP variable in JavaScript [duplicate]
(3 answers)
Closed 9 years ago.
Hello I am begginner in php.
I create a ecommerce site .
first I fetch all information from database.
all is going correct but I have problem in quantity input
when I insert quantity value then the total calculate in total .
I use js but I don't know to fetch the price value from database and store in javascript variable.
the code is :
<?php
echo "ISBN:". $row['isbn']."<br/>";
echo "Publisher:". $row['publisher']."<br/>";
echo "Year:". $row['year']."<br/>";
echo "Price:". $row['price']."<br/>";
?>
Qty : <input type="text" name="qty1" id="qty"/><br>
Total : <input type="text" name="total" id="total"/>
Sum
<script>
window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sum = 0;
var q = $row['price']; //how to resolve this line
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum = parseInt(ip.value)*q || 0;
}
}
result.value = sum;
}
</script>
you can combine javascript and php functionality by simply telling the parser to "print into the javascript". when the html file is "viewed" by the client, the javascript is beeing executed.
var q = parseFloat(<?php echo $row['price']; ?>);
pay attention that $row['price'] contains a number with a . as decimal dot - like 10.33 and the line
; ?>;
fist ; is the end from the php variable declation and second ; - after ?> is to end the variable declation from javascript.
Note - this only works when the Javascript Code an the HTML content is on the same Page. When dealing with an external Javascript Source - write in your PHP something like this
echo '<script>var q = "' . $row['sum'] . '";</script>";
and then use q in your external js file
I have a php array and I want to add its value to a javascript array. For example I am doing it something like this.
$k_data = json_encode($k)
Thus
k_data = [2,3,4,8,9]
Now in javascript I am doing like the following
var s4 = [[]];
for(var i = 0; i<5; i++)
{
s4.push([i,$k_data[i]]);
}
plot5.series[0].data = s4;
where plot5 is jqplot graph. But this is not working, I am getting blank graph while the following thing is working
for(var i = 0; i<5; i++)
{
s4.push([i,Math.sin(i)]);
}
Where I am making mistake?
If you want to deal with the php array only, you can do this-
First, implode the array to make a comma-separated string, say $str. Just like-
<?php
$str = implode(",", $array);
?>
Then, use split to convert the php string to the javascript array. Just like-
<script>
var str = <?php echo $str; ?>;
var array = str.split(',');
</script>
OR, json_encode() can help you directly-
<script>
<?php
$js_array = json_encode($php_array);
echo "var js_array = ". $js_array . ";\n";
?>
</script>
Well you can do a for loop and echo the Javascript commands to fill the Javascript Array
<script>
var s4 = [[]];
<?php
$k_data = json_encode($k)
$i = 0;
foreach($k_data as $v) {
echo 's4.push([' , $i , ',Math.sin(' , $v , ')]);';
++$i;
}
?>
plot5.series[0].data = s4;
</script>
It seems that you are refering to a php variable in you javascript. Keep in mind that PHP is executed serverside, whereas javascript is executed by the browser. Therefore, you need to pass the PHP variable to your javascript. Assuming that your javascript and PHP are in one .php file, replacing above javascript with the following should work:
<?php $k_data_js = implode("','", $k_data); ?>
var k_data = <?php echo "['" . $k_data_js . "']"; ?>;
var s4 = [[]];
for(var i = 0; i<k_data.length; i++)
{
s4.push([i,k_data[i]]);
}
plot5.series[0].data = s4;
The variable is passed to javascript in the second line. From then on you can refer to k_data in your script.