-1

Possible Duplicate:
Creating jQuery AJAX requests to a PHP function

How can i write PHP in Jquery

is there is a way to do this

    $('button').click(function(){
       <?php  session_destroy();?>
      }) ; 
Community
  • 1
  • 1
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • Your PHP code will be returned, and then returned to the client. What you'd want to do is use an AJAX call or other HTTP Get to a URL on your site to execute the session destroy. – p.campbell Jul 12 '12 at 13:43
  • php code with js? create a session_destory.php you can call – silly Jul 12 '12 at 13:44
  • 2
    Well if you are destroying the session. One would imagine you are logging out or some similar task. Why not allow the button to navigate to the page directly... kill the session then redirect from the server to your landing page (login or other) – rlemon Jul 12 '12 at 13:47

3 Answers3

11

You can't execute PHP client-side.

But

You can call a php script on click to do what you want:

$('button').click(function(){
   $.get("destroySession.php");
}); 

You can also get or post some values:

var values = {
     destroy: true
};

//get request:
$.get("destroySession.php", values);

//post request:
$.post("destroySession.php", values);
Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • can you call a php function or it has to be a php file – Mina Gabriel Jul 12 '12 at 13:46
  • @MinaGabriel php file. You can't execute php (server side) code on the client (browser) side. – Naftali Jul 12 '12 at 13:47
  • 1
    you can call a file and pass arguments using `$.get("destroySession.php?foo=bar");` or POSTing them and have that determine the action to take in the PHP file (calling specific functions with or without arguments) – rlemon Jul 12 '12 at 13:53
  • @rlemon that is **not** the right way to use `$.get` – Naftali Jul 12 '12 at 13:54
  • @Neal this question has been answered more than a few times. I can probably find 10 or more examples on the site. – rlemon Jul 12 '12 at 13:55
1

You can't execute PHP client-side.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
1

You cannot. PHP is interpreted on the server side and jQuery is interpreted on the client side.

You should either use an anchor <a href="session_destroy.php"> to go to another PHP page and destroy the session or use AJAX to call the destroy function without leaving the page.

jQuery('button').click( function () { jQuery.get("session_destroy.php"); } );
Rawkode
  • 21,990
  • 5
  • 38
  • 45