How to execute a PHP function from JavaScript?

I’m having trouble running a PHP function within my JavaScript code. Here’s what I’ve tried:

function emptyTable() {
  let query = 'DELETE FROM products';
  if (!db.execute(query)) {
    console.log('Query failed');
    return;
  }
  console.log('Table emptied');
}

document.write(`
<script>
function handleButtonClick() {
  <?php emptyTable(); ?> // This doesn't work
}
</script>
`);

I’ve also attempted ‘<?php emptyTable(); ?>’, “<?php emptyTable(); ?>”, and just emptyTable();

What am I doing wrong? How can I make this work? Any help would be great!

I’ve dealt with similar issues before, and there’s a fundamental misunderstanding here. JavaScript runs on the client-side (browser), while PHP executes on the server-side. They can’t directly interact like that.

Instead, you need to use AJAX to send a request from JavaScript to a PHP script on your server. Here’s a basic approach:

  1. Create a PHP file (e.g., ‘empty_table.php’) that handles the database operation.
  2. Use JavaScript to send an AJAX request to this PHP file.
  3. Process the response in JavaScript.

I’ve found this method reliable for similar tasks. It keeps your code cleaner and maintains proper separation between client and server logic. Just remember to implement proper security measures, like user authentication, to prevent unauthorized database access.

hey mate, u can’t mix PHP n JS like that. They don’t play nice together directly. what u need is AJAX. Make a separate PHP file for ur database stuff, then use JS to send a request to it. It’s like a middleman between ur JS and PHP. works great for me everytime. give it a shot!

It appears that mixing client-side and server-side code is causing the difficulty. PHP is executed on the server before the page is delivered and rendered in the browser, whereas JavaScript is executed after the page loads. To handle the operation you want, consider using AJAX. For example, establish a separate PHP file to perform the database manipulation and have your JavaScript code send an AJAX request to it. The PHP file can then process the query, send a response back, and your script can handle that response accordingly. This approach maintains a clear separation between client and server responsibilities, and it provides a more secure and manageable solution for interfacing with your database.