I am trying to execute a simple PHP script on click of a <div>. I've searched around SO and some similar questions appear, but all deal with posting data when I have no data to post.
<div name="logout">
logout
</div>
<script>
$(document).ready(function() {
$('div[name="logout"]').click(function() {
$.ajax({
url: './scripts/logout.php',
dataType: 'json'
}).done(function(result) {
alert(result.message);
});
});
});
</script>
logout.php is as below:
if (isset($_SESSION["username"]) && (isset($_SESSION["logintoken"]))) {
session_destroy();
$jsonArr = array('success' => true, 'message' => "You've logged out.");
echo json_encode($jsonArr);
} else {
$jsonArr = array('success' => false, 'message' => "You're not logged in.");
echo json_encode($jsonArr);
}
No alert is made on click and console shows no errors. Adding a .fail condition to the AJAX call pops every time, but again nothing is in console.
All other times I use AJAX it's to handle forms, not quite this exact circumstance. I have no data to post or get, and most solutions on SO say to add a data: {} bit to the AJAX call, but I'd have nothing to put here.
What have I done wrong here? Tracing through my code, I figured maybe I was reinitializing $_SESSION variables, but I haven't.
networktab of the developer tools. That will show you if you are having trouble with the request and not a JS error. Just a shot in the dark, but are you rewriting urls at all? This is the sort of thing you see when you are using relative paths to files in the ajax url. You likely need to use a full path or at least relative to the root. Rewriting a url like/post/{id}/topost.php?id={id}will mean that the request is going to/post/{id}/scripts/logout.phpand the file won't exist under that directory.networktab. It's showing the correct path to the page and it's got the green circle icon with "OK" beside it.