0

Hello need help to run the following php in a html.

function runMyFunction(){
      $_SESSION["identificate"] = 'no';
      session_destroy();
      header('Location: Login.html');
}
---------------------------------------------------------
 <div id="foo">
    <button type="button" onclick="runMyFunction()">Logout

    </button>
 </div>

Thanks

1
  • PHP is a serverside language. This means it's performed before the visitor sees the output in the browser. The best solution would be to create a redirect with Javascript towards the php file and use header('location: .. ') to send them back again or use Ajax. Commented Nov 28, 2015 at 17:14

1 Answer 1

2

You should execute an ajax call with the help of jQuery.
We can use the shorthand method .post to issue a post request directly.

First put the php code in a separate file, called logout.php

logout.php

function runMyFunction(){
      $_SESSION["identificate"] = 'no';
      session_destroy();

      //header('Location: Login.html'); we will move the redirect to the success handler of the ajax call
}

//call the function
runMyFunction();

Then in the html, include jquery and add a script block like below

<script type="text/javascript">
$(function() {
    $("#foo button").click(function(){
        $.post( "logout.php", function( data ) {
            console.log("success");
            window.location = "login.html"; // redirect moved here, after the logout happened successfully
        });
    })
});
</script>

You can remove the onclick attribute from the button, so your button html will become this

<button type="button">Logout</button>

This is how you include jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Sign up to request clarification or add additional context in comments.

11 Comments

If you're going to use $("#foo button") then the button requires an id.
foo is the id of the div containing the button, button doesn't need id. Unless I'm missing something.
ah, you're probably right Alex. My mistake ;-)
edited the answer to move the redirect in the ajax success callback
Im sorry i am working with php and html so i don't know much about js and jquery. That script you made will modify like what my button 'foo' will do? where in that script do i write my "runMyfunction()" so that when i click the button it will execute it?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.