简体   繁体   中英

Can I use jQuery and AJAX to execute php code written in the same file?

I searched a lot and all I found out was that AJAX is used to execute a php code in another file. I want to know if it is possible and if yes then how do I execute a php code that is written in the same file.
Here is my jQuery code...

$(document).ready(function(){
    $("#logout").click(function(){
        //execute the php code here.
    });
});


And here is the php code i want to execute

<?php
    session_unset();
    session_destroy();
?>

Basically, to give an overview of what I am trying to achieve, I am using a button with id="logout" to stop the session and logout of the webpage.

In short, yes, you can use ajax to run some php code that was found in the same file that was used to render the page you are viewing.

You may want to go a different route in this case since logging out usually means that some of the items that a user can see on the page should no longer be accessed by the user. Implementing the logout button as a link that reloads the entire page can be a good way to go.

To accomplish what your question details, you could add this php at the top of your page.

if ( isset( $_POST['logout'] ) ) {
   session_unset();
   session_destroy();
   die();
}

This way, a post request with a logout parameter will trigger this code. Now in the jQuery, you need to send a post to this url with the logout parameter set.

let data = {
   'logout' : true
};

$.post( window.location, data );

Checkout https://api.jquery.com/jquery.post/ and https://api.jquery.com/jQuery.ajax/ for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM