When I click onto a button of my page, I do the following action :
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(){
alert("Vote done");
}
Then, the page of the url receive my POST variable to treat the vote:
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
开发者_开发百科 $authorization_vote=false;
}else{
$authorization_vote=true;
}
I would like to get back and send $autorisation_vote to AJAX or jQuery in order to alert the user if his vote has been done. I heard about callback but don't succeed to adapt to my case. How do that ?
there's a couple of ways you could do it.
The quick and dirty way is to just echo "true" or "false" in your PHP and that will be available in to the callback function if you declare it like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
or you could set the http header to return a status code, which would allow you to declare two call backs in your ajax call on success or failure
The php would look like this
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
header("HTTP/1.0 423 Locked"); // The resource that is being accessed is locked
}else{
header("HTTP/1.0 204 No Content"); // Processed, but not returning content
}
and your ajax call could look like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
statusCode: {
204: function(){ alert("Vote cast"); },
423: function(){ alert("Vote not cast for whatever reason..."); }
}
Which is probably a bit of overkill, but it's good to know these things.
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
(note added data
)
and in your php script add
echo "vote done and some data here";
because true
is changed to 1 and false
would be blank
So example:
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
echo "voted";
}else{
$authorization_vote=true;
echo "vote failed";
}
精彩评论