Reputation: 907
I have tried to pass a PHP variable in Javascript and it's not working. Please find the code I am using below:
function delete_id(id)
{
if(confirm('Are you sure you want to permanently delete this record?'))
{
window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id=<?php echo $estimate_id; ?>';
}
}
Maybe I need to edit the code that's calling the JS? Here it is below:
<a href='javascript:delete_id(".$rows['estimates_cabinet_id'].")'>DELETE</a>
Can anyone see what I need to do to get this working?
Thanks,
John
Upvotes: 0
Views: 46
Reputation: 579
You will not be able to use php from your javascript file. Some common ways to 'pass the variable' to the javascript could be to print it out in your html page:
index.html
<script>
var estimate_id = <?php echo $estimate_id; ?>;
</script>
main.js
esitmate_id is now available as a global variable.
function delete_id(id)
{
if(confirm('Are you sure you want to permanently delete this record?'))
{
window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id='+estimate_id;
}
}
Or you could just use your current code in the index.php file in a script tag
Upvotes: 2
Reputation: 6953
According to you comments it looks like you have a valid php-script, in which you link to a js-file (via <script src=...>
).
Php inside such a js file will not be executed as php, but simply be sent to the browser as is.
So the easy solution would be to move that js code to your php file, where you output html:
<?php
$estimate_id=1;
?>
<html>
<script>
function delete_id(id)
{
if(confirm('Are you sure you want to permanently delete this record?'))
{
window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id=<?php echo $estimate_id; ?>';
}
}
</script>
<?php
// more php...
?>
Another solution could be to make your server execute js-files as php.
This can be tricky (you cannot simply pass params, you have higher security risk), but would work - I would not recommend that.
Upvotes: 0