0

I created an onclick javascript function and the idea is to send values in the database table in every click of the button/a href but it seems that in every time I reload/open the page in the web it sends and runs every single function/query automatically.

This the function in my html file

//audit trail
function auditPrint(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','printed receipt')");
  ?>
}
function auditCancel(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','canceled transaction')");
  ?>
}
function auditLogout(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','logged out')");
  ?>
}

It works fine but I would like it to send only if I click the button. Is there a way I can fix it?

Syscall
  • 19,327
  • 10
  • 37
  • 52
  • 1
    Are you trying to put PHP inside JavaScript function? See [What is the difference between client-side and server-side programming?](https://stackoverflow.com/q/13840429/9193372) – Syscall Jan 10 '23 at 18:58
  • All PHP gets run on the server side before any output gets sent to the client browser. You'll need to make separate AJAX hits for each function. – Alex Howansky Jan 10 '23 at 19:00
  • @Syscall yes... – Joseph Dipol Jan 10 '23 at 19:00
  • ...but you can't. Please read q&a of the link above and use AJAX instead, as mentioned by @AlexHowansky. There are many examples on StackOverflow. – Syscall Jan 10 '23 at 19:02
  • 1
    @JosephDipol That's not possible, at least not in the way you're trying to do it. Think of communication between the front-end and the back-end as two separate one-way channels. PHP code is ran and data is injected into the page before it's returned to the client. Once it's returned to the client, the only way the client can report back to the server to get additional data is via another web request. – Jesse Jan 10 '23 at 19:03

0 Answers0