I have the content of a div being generated like this...
<div class="messagecount">
<?php
$mesagecount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . $wpdb->base_prefix . "messages WHERE message_to_user_ID = %d", $user_ID));
echo $messagecount;
?>
</div>
I am also using fancybox to popup a message, I have the callback set so that when I close the fancybox I can call a command, but now I want to be able to refresh the messagecount div without refreshing the page.
Can I do this using ajax in combination with the fancybox close callback?
Yes. First, assign to your div id "messagecount". Then, put in the head section of your document the following code:
<script>
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject){
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
}
}
}
else if (window.XMLHttpRequest)
return new XMLHttpRequest()
else
return false
}
</script>
Now, create load.php and put into it:
<?php
$mesagecount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . $wpdb->base_prefix . "messages WHERE message_to_user_ID = %d", $user_ID));
echo $messagecount;
?>
To reload the box, just put the following code after it:
<a href="#" onclick="sending(); return false;">Reload</a>
<script>
function sending(){
document.getElementById("messagecount").innerHTML="Refreshing"
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("messagecount").innerHTML=mypostrequest.responseText
}
else{
document.getElementById("messagecount").innerHTML='Woops! An error occurred. Please check your Internet connection and try again.';
}
}
}
mypostrequest.open("GET", "load.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
}
</script>