0

I have 2 variable in php, $title and $id. I put it on javascript function as parameter. in Javascript function, I want change a parameter to object ini php, How to fix it?

<body>
<?php
    $title = 'banner';
    $id = 2;
?>
<button onClick="<?php echo delete_list('$title', '$id'); ?>">Click</button>

<script type="text/javascript">
    function delete_list(item, item_id)
    {
        <?php 
             $x ='<script>item</script>'; 
             $y = '<script>item_id</script>';

             delete_table($x, $y);
        ?> 
    }
</script>
</body>
  • 3
    JavaScript is a client-side language, PHP is a server-side language. Therefor your PHP won't know that `delete_list()` is a JS-function. Echo that out as well, as such: `echo "delete_list('$title', '$id')";` – Qirel Sep 09 '15 at 18:06
  • 2
    PHP runs on your server and *generates* an HTML page (that may contain JavaScript). That HTML and JavaScript are ran by the browser. By that time, PHP is done and the connection is closed. For this to work, you need to make a new request to the server. You can use AJAX or even just a simple `
    ` POST.
    – gen_Eric Sep 09 '15 at 18:06

2 Answers2

0

You can't do it directly as you are trying to do. You'll have to make an AJAX request (passing the parameters x and y via POST or GET) to a PHP script that performs the action that you want. In this case, a script like:

<?php
delete_table($_GET['x'], $_GET['y']);
?>

(PS. Of course you need to sanitize the input)

mynx
  • 68
  • 4
The Coding Monk
  • 7,684
  • 12
  • 41
  • 56
0

You can do it with using ajax method. Basically here is an jQuery Post example:

function delete_list(item, item_id)
{
  $.post( "test.php", { item: item, item_id: item_id })
  .done(function( data ) {
    alert("Table deleted");
  });
}
Emre Tekince
  • 1,723
  • 5
  • 18
  • 30