John Davidson

Is possible to put javascript variable in php function in for loop?

0 comments
Message:


Is somehow possible to put javascript variable in eval echo? I tried a lot of possibilities, but everything crashed. It can work without Eval() function, but in that way, you can't quote "cal_days_in_month".


 <script>
for (var i = 1; i < <?php eval("echo cal_days_in_month(CAL_GREGORIAN, ".'<script>variable</script>'." , 2022) + 1;");?>; i++) {

if (i==8 || i == 15 || i == 22 || i == 29) { //10 19 28
document.write("<tr>");
}

document.write("<td class='cc'>"+ i +"</td>");
}

document.write("<tr>"); //konec else závorka

</script>



My Answer:
Yes, it is possible to use a JavaScript variable in a PHP function within a loop. However, it is important to note that JavaScript runs on the client-side and PHP runs on the server-side, so you cannot directly pass a JavaScript variable to a PHP function.

One way to achieve this is by using AJAX to send the JavaScript variable to a PHP script on the server, where it can then be used in a PHP function within a loop.

As for using `eval` in PHP to echo a JavaScript variable, it is not recommended as it can be a security risk. Instead, you can use `json_encode` to pass the JavaScript variable to PHP and then echo it out.

Here is an example of how you can achieve this:

JavaScript:
javascript
var jsVariable = "Hello";
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { jsVariable: jsVariable },
success: function(response) {
console.log(response);
}
});


PHP (your_php_script.php):
php
$jsVariable = $_POST['jsVariable'];
echo json_encode($jsVariable);


This way, you can pass a JavaScript variable to a PHP function within a loop using AJAX and avoid using `eval` in PHP.

Rate this post

3 of 5 based on 1998 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us