This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am tr开发者_开发百科ying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php
file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.
Here's my code:
$(document).ready(function() {
// Expand Panel
$("#open").click(function(){
//when the user clicks the logout button
$.ajax({
url: "logout.php"
)};
});
});
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li><?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?></li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#">Log Out</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
I suppose that you expect the output of the logout.php file to show. I think that your code might be working but that you forgot to tell the ajax where to put the data that it receives.
Try something like this:
$.ajax({
url: 'logout.php',
success: function(data) {
$('.result').html(data);
alert('Logout completed.');
}
});
Where "result" points to the div you want to load the response into.
Using $.ajax isn't the same as clicking regular links. $.ajax doesn't "follow" the link, it loads the data from that link into the document without refreshing the page.
What you need to do is do what you want in your logout.php file and then you sent information on whether logout succeeded or not. You do that by outputting HTML, XML or JSON, which you check in your javascript code and take appropriate action (redirect user, lock down the UI or whatever).
Try doing this:
$(document).ready(function() {
alert('loaded!')
// Expand Panel
$("#open").click(function(){
//when the user clicks the logout button
$.ajax({
url: "logout.php"
)};
alert('clicked!')
});
});
If this displays a popup saying clicked! then the event is being triggered. Tell me what happens so we can narrow it down to the $.ajax failing or the click event not being triggered.
If you are using firebug then you can go to the console panel and inspect XmlHttpRequests to closely look at any responses coming back from the remote script, if you have sent any back from the script that is.
精彩评论