i am working on one buddy press theme and want to display unread messages count via ajax.
i have bellow code in function.php of my theme
<?php
function addMessageRefresh()
{
?>
<script type="text/javascript">
function getMessages(){
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
}
setInterval("getMessages()", 10000);
</script>
<?php
}
add_action( 'wp_head', 'addMessageRefresh');
?>
it worked.
but its only show unread count on page load, but if user receive any message this did’t update.
the main purpose of this script is to display total number of unread messages and it should update via ajax means if user receive any message, it should show total number of unread messages without reloading page.
Thanks
somehow it..
function getMessages(){
jQuery.ajax({
url: '../url.php'
dataType: 'html',
success: function (data) {
jQuery('#user-messages span').text("Unread Messages: " + data);
}}
)
}
../url.php code
<?php echo messages_get_unread_count(); ?>
There are several steps, that you need to do:
1) Place element which contain unread message count. This should be adde to your template.
<div id="unread_messages"></div>
2) Add javascript code which will update your count value.You can add this to your template or you can print it from wp_head/wp_footer hooks
<script type="text/javascript">
function update_unread_count() {
jQuery('#unread_messages').load(
'<?php echo admin_url('admin-ajax.php'); ?>',
{ 'action': 'get_unread_message_count' }
);
}
jQuery(document).ready(function() {
// update every 15 seconds, after page loaded
setInterval('update_unread_count()', 15000);
});
</script>
3) Register ajax request handler. You should add this lines into your functions.php theme file
function my_get_unread_message_count() {
echo messages_get_unread_count();
die();
}
add_action('wp_ajax_get_unread_message_count', 'my_get_unread_message_count');
Something like that.
Your issue lies within:
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
What is being done is when the page is being loaded PHP processes the messages_get_unread_count() function and uses that value to render the page. From there the generated JavaScript will be called at your interval but it will have a static value defined in your preprocessed markup.
You will need to have an AJAX call to a url that will return your message count.
This is the functionality to allow you to get the updated message count.
function add_message_count_js() {
?>
<script type="text/javascript">
//<![CDATA[
var msg_count;
function updateMessages() {
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {"action": "view_message_count"},
success: function(data) {
jQuery('#user-messages span').text("Unread Messages: "+data);
}
});
return false;
}
setInterval('updateMessages()', 10000);
//]]>
</script>
<?php
}
add_action('wp_head', 'add_message_count_js');
This will add the appropriate AJAX hooks.
add_action('wp_ajax_view_message_count', 'view_message_count');
add_action('wp_ajax_nopriv_view_message_count', 'view_message_count');
function view_message_count() {
if (is_user_logged_in())
echo messages_get_unread_count();
die();
}
Both of these snippets should go in your functions.php file.
Related
I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
little issue over here.
I have a php function that is called via AJAX and looks like this:
function processActiveDirectory(){
$var = new GetLDAPUsers;
echo "Getting Users from Active Directory.... <br />";
$adusers = $var->getAllUsers();
echo "setting up images.... <br />";
// processing more stuff
echo "finished";
}
I'm trying to get a "live- log" echo. Meaning before every step the echo should output to a Log area, one step after another. So the user knows what's going on.
But the Problem is, that the log doesn't appear during the process, it just fills in at the whole text at the end of the process. Everything else works fine. The Log just doesn't appear at runtime, but after the function is finished it appears at the right position.
My AJAX call:
jQuery(document).ready(function($) {
$('#lii-form').submit(function() {
data = {
action: 'lii_map_images'
};
$.post(ajaxurl, data, function(response){
$('#lii_log').html(response);
});
return false;
});
});
This is how it's build:
Edit
Other than in this thread I'm already using an ajax call, to call the function. It's within the called function that I'm echoing stuff...
Edit 2
I'm using wordpress
Sorry I can't offer more informations, because of enterprise restrictments.
This is a short over-view on your need. Please develop further with this idea.
This uses two AJAX calling - one for the main process and other for progress:
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//Start the main process
$.ajax({
url: 'main.php',
success: function(data) {
}
});
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
$("#progress").html(data);
if(data != "finished"){
getProgress();
}
}
});
}
//Start the progress section
getProgress();
</script>
<div id="progress"></div>
main.php
<?php
$arr = ['Getting Users from Active Directory....','setting up images....','finished'];
foreach($arr as $value) {
session_start();
$_SESSION["progress"]=$value;
session_write_close();
sleep(1);
}
progress.php
<?php
session_start();
sleep(1);
echo $_SESSION["progress"];
So your processActiveDirectory will come under Main.php and echo should be replaced with SESSION variable
I think there is no need in such thing as LOG process WITH AJAX. AJAX is too heavy thing and it could be a bad design if you want it. It's better to use web sockets or not use at all
I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>
I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.
In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins
<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>
WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})
I've create a page that load 10 elements and at the bottom of the page I've placed the classic button "load more" to load 10 more elements.
The problem is with jQuery, the style given by :nth-child() property doesn't work for the next 10 elements and so on.
Is there a solution to solve this problem?
E.g.:
File main.js
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
File example.php
<script type="text/javascript">
$('#more_button').click(function(){
loaded_messages += 10;
$('#loading').ajaxSend(function() {
$("#loading").stop(true,true).fadeIn().delay(200).fadeOut();
});
var dati = "twitterpagination/get_messages/" + loaded_messages;
$.ajax({
url:'twitterpagination/get_messages/' + loaded_messages,
type: 'get',
data: dati,
cache: false,
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
});
if(loaded_messages >= num_messages - 10) {
$("#more_button").hide();
}
},
error: function() {
// do nothing
}
});
return false;
});
</script>
<div id="main">
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
<div id="more_button">more</div>
</div>
File loaded by Ajax url:
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
In the file loaded by ajax:
<?php
foreach($latest_messages as $message) {
echo '<p class="small-product-wrapper">'.$message->message .'</p>';
}
?>
Add the style to the returned P tag
You need to re-run those 2 jQuery lines right after the new html is added from your AJAX.
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
// here
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
});
}
This is because those original lines are run only once when the page is loaded.
When you load new content with Ajax the only way to have the style automatically assigned to it it's to give it a class and have that class style defined in css.
If you don't do that, you have to assign the style again in the callback function of the ajax call.