How to send ajax request in wordpress without displaying zero - php

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
}
?>

Related

Woocommerce aJax apply coupon code to basket

I am attempting to apply a coupon code to the basket on a button press.
I have the following code:-
coupon = jQuery(this).data('coupon');
data = {coupon_code : coupon};
jQuery.post( "?wc-ajax=apply-coupon", { coupon_code: coupon }).done(function( data ) {
alert( "Data Loaded: " + data );
});
I can see the following data is being parsed to the server:-
coupon_code: 10percentdiscount
The 10percentdiscount exists.
The Server is not sending back a response once I have sent the request.
Am I correctly making this request or is there another way?
Thank you in advance.
You don't need to add custom code in your functions.php. Woocommerce supports adding coupons via AJAX natively (see how below).
Errors in your code:
You forgot to send the nonce (security parameter);
It is apply_coupon not apply-coupon (underscore vs dash);
Your URL should start with a slash "/?wc-ajax=apply_coupon";
Correct version:
var data = {
coupon_code: jQuery(this).data('coupon'),
security: '<?php echo wp_create_nonce("apply-coupon") ?>'
};
jQuery.post('/?wc-ajax=apply_coupon', data).done(function(data) {
alert("Data Loaded: " + data);
});
I would do so:
Define ajax url in header.php or in page would you add coupon
<script type="text/javascript" language="javascript">
var ajax_url = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php";
</script>
In function.php you must define ajax call
function implement_ajax() {
include(TEMPLATEPATH . '/ajax_return.php');
}
add_action('wp_ajax_my_special_action', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax');
In ajax_return.php you past code that add coupon to woocommerce:
if (isset($_POST['couponcode']))
{ apply_coupon($_POST['couponcode']); };
function apply_coupon($couponcode) {
global $woocommerce; WC()->cart->remove_coupons();
$ret = WC()->cart->add_discount( $couponcode );
$array = array('return' => $ret); print_r($array);
}
exit;
Your jQuery.post will became this:
<script type="text/javascript">
jQuery(function(){
coupon = jQuery(this).data('coupon');
jQuery.post(ajax_url, {action : 'my_special_action', couponcode : coupon}, return_function, 'JSON');
});
function return_function(data)
{
console.log(data.return); //contains true if coupon was applied
}
</script>
If you need, call return_function to manage response.

how to load wordpress comments using ajax when user scroll upto comment div

i have been trying to do this past 2 days but no success.
here is my code.
var elementOffse = $('#loadComments').offset().top;
var heigh = $(window).height();
$(window).scroll(function()
{
var scrollTopp = $(window).scrollTop();
if (scrollTopp >= (elementOffse - heigh) && loaded == 0)
{
loaded = 1;
$('#loadComments').html('Downloading...'); // Show "Downloading..."
$.ajax({
type: "GET",
url: "loadComments.php"
}).done(function(data) { // data what is sent back by the php page
$('#loadComments').html(data); // display data
});
}
});
in loadComments.php i call the function 'comments_template();'.
i want to load the comments in #loadComments after it is queried.
any help would be appreciated. thank you.
Wordpress has a built in AJAX handler, and using this ensures that your AJAX requests can access all the goodness of WP.
I can't say for sure without seeing logs, but if you are doing something with comments, it's likely that a WP core function is involved, and as a generic AJAX call won't include them, an error could be thrown.
Here is some JS that should do the trick -
var elementOffse = $('#loadComments').offset().top;
var heigh = $(window).height();
$(window).scroll(function(){
var scrollTopp = $(window).scrollTop();
if (scrollTopp >= (elementOffse - heigh) && loaded == 0){
loaded = 1;
$('#loadComments').html('Downloading...'); // Show "Downloading..."
var data = {
type: 'GET',
action: 'load-comments'
};
$.post(ajax_object.ajaxurl, data, function(response){
$('#loadComments').html(response);
});
}
});
PHP - Place this in functions.php (or any other custom included file if you wish) -
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' ); // If user is not logged in
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' ); // If user is logged in
function my_ajax(){
{...do your comments stuff here...}
die(); // Required for a proper Wordpress AJAX result
}
Finally, to ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to functions.php (or any other custom included file if you wish).
<?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
}
?>

how to call external php file in WordPress using ajax

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})

buddy press ajax new message notifiction

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.

AJAX: Send and retrieve a value with jquery post() and PHP, WordPress

I'm trying to make the following happen in a WordPress page:
User clicks on a "sort posts by" button
Value from the button is sent to sortFilter.php page
Current page is refreshed and uses the value posted in sortFilter.php to create a new loop.
On the initial page there is a tag that I want to load the data into:
<p id="sortFilter"></p>
Here is the code I'm using, and it doesn't seem to be working (nothing is being loaded into the #sortFilter p)
$(document).ready(function() {
setInterval(function(){
$("#sortFilter").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/");
},1000);
//Filter Categories
$.ajaxSetup({cache:true});
$('#byAuthorCtrl ul li').click( function() {
$.post("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/", {id: "testValue"}
);
});
});
then on sortFilter.php:
<?php
/*
Template Name: sortFilter
*/
$id = $_POST['id'];
echo $id;
?>
Right now I'm just using a test value to try to post to the page.
WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery.ajax({
type:'POST',
data:{
action:'my_unique_action',
id:'testValue'
},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action','doMyCustomAjax');
Use both if you want it to work for everybody.
Here's the doAjax function, for example:
function doMyCustomAjax(){
$id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
if( empty( $id ) )
return;
echo $id;
}
Put that in functions.php too. That will return the id you send in AJAX.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Put the add_action lines in the functions.php file. The admin-ajax.php file will run some functions and then runs the hook that your 'action' value makes, then kills the script. I've modified the code above to reflect this information.
Ok... sorry to use the Answer to add a comment, but it will be much easier to elaborate with the code display here.
So, I have the following in my functions.php:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');
function doMyCustomAjax(){
$id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
if( empty( $id ) )
return;
echo $id;
}
the following script in footer.php to be executed on my category archive:
<script type="text/javascript">
$(document).ready(function() {
//Filter Categories
$.ajaxSetup({cache:true});
$('#byAuthorCtrl ul li').click( function() {
jQuery.ajax({
type:'POST',
data:{id:'my_unique_action'},
url: "http://www.theknotcollective.com/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
</script>
and the following at the top of my category.php:
<p id="sortFilter"><?php doMyCustomAjax(); ?></p>
Again my goal is to post that "id" variable once the link is clicked, then retrieve it once the page has been reloaded, in order to end up with a different loop on page refresh.
I'm new to ajax and this type of PHP function so I don't quite understand what's going on here, and obviously I'm missing something / doing something wrong. If you could elaborate a little I'd really appreciate it!
Thx!

Categories