How to Run PHP in Javascript / JQuery

Hello all, nice to meet you.

So i have a problem to add logs for when logout in my web project, and the problem is like this:

I have a code to record activity log like this :

$name = $this->session->userdata('UserProfile');
		$logdata = array(
						  'userid'=>$name->username,
						  'activity'=>'Logout BO',
						  'param'=>''
						);
		$this->base->log_activity($logdata);

and i want it to put and running only when this jquery is clicked (this code below is for logout), so i add the code and put it like this:

$(".js__logout").on("click",function(){
         window.location.href = localStorage.getItem("SystemUrl"); //back to login menu
	<?php
                $name = $this->session->userdata('UserProfile');
		$logdata = array( 'userid'=>$name->username,
				            'activity'=>'Logout BO',
				            'param'=>''
						);
		$this->base->log_activity($logdata);
        ?>
				
});

And the problem is, when i refresh the webpage and not yet do logout (button with class js__logout isnt yet clicked), i see the program was sent that logdata to my database.
So everytime i going to this webpage (example: user activity log) , its everytime too it will record logactivity “Logout BO” to my database.

Here’s the example :

image

Am i wrong with calling that php code? Or is that must be a condition to deal with it? Please help me :slight_smile:
Thank you so much

PHP executes on the server.
Javascript executes on the client.
They do not run at the same time.

PHP runs first, on the server, and processes all of its code. It doesnt read anything not inside <?php ?> tags.
Once PHP is done, all of it’s code blocks have disappeared, leaving only HTML/JS/CSS behind. This then gets handed to the client. You can see what this looks like by View Source’ing the page from inside your browser.
The client then runs any javascript, forms the HTML, and presents the view to the user.

Never do the worlds run at the same time; the closest that comes to interaction between the two is AJAX, which is just the client executing another request to the server in the background, usually passing data to a script that sends back a response that the Javascript parses.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.