I am attempting to add auto complete search function in Wordpress, I have the code but auto complete does not trigger when i start typing in the search field, anybody can guide me in the right direction?
//php
add_action( 'init', 'casino_autocomplete_init' );
function casino_autocomplete_init() {
// Register our jQuery UI style and our custom javascript file
wp_enqueue_style('mycasino-jquery-ui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css');
wp_enqueue_script( 'my_acsearch', get_template_directory_uri() . '/js/myacsearch.js', array('jquery','jquery-ui-autocomplete'),null,true);
wp_localize_script( 'my_acsearch', 'MyAcSearch', array('url' => admin_url( 'admin-ajax.php' )));
// Function to fire whenever search form is displayed
add_action( 'get_search_form', 'mycasino_autocomplete_search_form' );
// Functions to deal with the AJAX request - one for logged in users, the other for non-logged in users.
add_action( 'wp_ajax_casino_autocompletesearch', 'mycasino_autocomplete_suggestions' );
add_action( 'wp_ajax_nopriv_casino_autocompletesearch', 'mycasino_autocomplete_suggestions' );
}
function mycasino_autocomplete_search_form(){
wp_enqueue_script( 'my_acsearch' );
wp_enqueue_style( 'mycasino-jquery-ui' );
}
function mycasino_autocomplete_suggestions(){
// custom post type
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', array('custom_post', 'events'));
};
return $query;
};
add_filter('pre_get_posts', 'filter_search');
// Query for suggestions
$posts = get_posts( array(
's' =>$_REQUEST['term'],
) );
// Initialise suggestions array
$suggestions=array();
global $post;
foreach ($posts as $post): setup_postdata($post);
// Initialise suggestion array
$suggestion = array();
$suggestion['label'] = esc_html($post->post_title);
$suggestion['link'] = get_permalink();
// Add suggestion to suggestions array
$suggestions[]= $suggestion;
endforeach;
// JSON encode and echo
$response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";
echo $response;
// Don't forget to exit!
exit;
}
// jquery
jQuery(document).ready(function ($){
var acs_action = "casino_autocompletesearch";
$("#s").autocomplete({
source: function(req, response){
$.getJSON(MyAcSearch.url+"?callback=?&action="+acs_action, req, response);
},
select: function(event, ui) {
window.location.href=ui.item.link;
},
minLength: 3,
});
});
Please make sure you're using get_search_form() for calls and not get_search_query() you can check this inside the themes php file where the search field has been created. The above code can only be used by themes that uses get_search_form()
Related
My ajax call on click redirects me to /undefined, /wp-admin/admin-ajax.php has value 0
I'm using Divi theme, custom ajax script which is localized:
function my_enqueue() {
wp_enqueue_script( 'increment_counter', get_stylesheet_directory_uri() . '/js/slug-ajax.min.js', array('jquery') );
wp_localize_script( 'increment_counter', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
Counter function:
add_action('wp_ajax_increment_counter', 'my_increment_counter');
add_action('wp_ajax_nopriv_increment_counter', 'my_increment_counter');
function my_increment_counter(){
// Name of the option
$option_name = 'my_click_counter';
// Check if the option is set already
if ( get_option( $option_name ) !== false ) {
$new_value = intval(get_option($option_name)) + 1;
// The option already exists, so update it.
update_option( $option_name, $new_value );
} else {
// The option hasn't been created yet, so add it with $autoload set to 'no'.
$deprecated = null;
$autoload = 'no';
add_option( $option_name, 1 , $deprecated, $autoload );
}
}
Ajax file has this jQuery code for increment counter:
jQuery(document).ready(function($){
$('.activate-popup-animation').click(function(e){
e.preventDefault();
$.ajax({
url: my_ajax_object.ajaxurl,
data: {
action: 'increment_counter',
},
type: 'POST',
})
.done(function(){
// go to the link they clicked
window.location = $(this).attr('href');
})
.fail(function(xhr){
console.log(xhr);
})
});
});
Now, plan is to create custom widget in dashboard and call this function:
get_option('my_click_counter')
Where I'm making mistake, is that url problem with call action?
Your ajax function should call some action, in this case "my_increment_counter", but instead you wrote "increment_counter", same with wordpress hooks. It should be:
add_action('wp_ajax_my_increment_counter', 'my_increment_counter');
add_action('wp_ajax_nopriv_my_increment_counter', 'my_increment_counter');
I've been working with WooCommerce recently and I was wondering if it was possible to get cart items via JavaScript or JQuery
I know you can use PHP functions to retrieve the contents of the cart but currently I do not have access to the backend of the site.
I've found a similar question here: WooCommerce cookies and sessions - Get the current products in cart
In the session there is a wc_fragment that contains the HTML of the cart.
{"div.widget_shopping_cart_content":"<div class=\"widget_shopping_cart_content\">\n\n\t<ul class=\"woocommerce-mini-cart cart_list product_list_widget \">\n\t\t\t\t\t\t<li class=\"woocommerce-mini-cart-item mini_cart_item\">\n\t\t\t\t\t×\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t<img width=\"800\" height=\"450\" src=\"https://cdn2.co.uk/app/uploads/Overlapped-800x450.jpg\" class=\"attachment-woocommerce_thumbnail size-woocommerce_thumbnail\" alt=\"\" />Raspberry Drinking Yogurt - 1 drink\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"quantity\">1 × <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>1.50</span></span>\t\t\t\t</li>\n\t\t\t\t\t</ul>\n\n\t<p class=\"woocommerce-mini-cart__total total\">\n\t\t<strong>Subtotal:</strong> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>1.50</span>\t</p>\n\n\t\n\t<p class=\"woocommerce-mini-cart__buttons buttons\">View basketCheckout</p>\n\n\t\n\n</div>"}
Would it be possible to extract the elements from this?
I've found a solution for you. Maybe there is a better one but's how I would do it.
First create a custom JS file and register it. Also add a custom ajaxurl (in case you don't did this already):
add_action( 'wp_enqueue_scripts', 'wp_enqueue_scripts_action' );
function wp_enqueue_scripts_action() {
wp_register_script( 'child-theme', get_stylesheet_directory_uri() . '/assets/child.js', [ 'jquery' ] );
wp_enqueue_script( 'child-theme' );
wp_localize_script( 'child-theme', 'child_theme', [
'ajaxurl' => admin_url( 'admin-ajax.php' )
]
);
}
Now add an AJAX endpoint:
add_action( 'wp_ajax_get_cart_items', 'wp_ajax_get_cart_items_action' );
add_action( 'wp_ajax_nopriv_get_cart_items', 'wp_ajax_get_cart_items_action' );
function wp_ajax_get_cart_items_action() {
$cart = WC()->cart;
if ( $cart ) {
wp_send_json_success( $cart->get_cart_contents() );
/** #noinspection ForgottenDebugOutputInspection */
wp_die();
}
}
This will return the content of the cart in case a cart is available. Now call it inside your JS function. In my case for testing directly in the document.ready method:
(function ( $ ) {
$( document ).ready( function () {
let data = {
action: 'get_cart_items'
};
$.post( child_theme.ajaxurl, data, function () {
} ).done( function ( response ) {
console.log( response );
} ).fail( function ( response ) {
console.log( 'Fail' );
} );
} );
})( jQuery );
This will return for example:
077e29b11be80ab57e1a2ecabb7da330: {key:
"077e29b11be80ab57e1a2ecabb7da330", product_id: 249, variation_id: 0,
variation: Array(0), quantity: 1, …}
I think you need to add some null checks but all in all its a working solution.
I have used Wordpress Admin Ajax and the console shows that 400 (Bad Request)
jQuery('#submitid').click(function(e){
e.preventDefault();
//var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: {status: 'status', name: 'name'},
success:function(data){
jQuery("#result").html(data);
}
});
});
The Wordpress AJAX process has some basic points that should be followed if you want it to work correctly:
1.In functions.php add the action you'd like to call from the frontend:
function logged_in_action_name() {
// your action if user is logged in
}
function not_logged_in_action_name() {
// your action if user is NOT logged in
}
add_action( 'wp_ajax_logged_in_action_name', 'logged_in_action_name' );
add_action( 'wp_ajax_nopriv_not_logged_in_action_name', 'not_logged_in_action_name' );
2.Register the localization object in functions.php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$some_object = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'some_handle', 'ajax_object', $some_object );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
3.Create the AJAX request on the frontend
// source: https://codex.wordpress.org/AJAX_in_Plugins
var data = {
'action': 'not_logged_in_action_name',
'whatever': 1234
};
jQuery.post( ajax_object.ajax_url, data, function( response ) {
console.log( response );
}
All Wordpress Ajax call must have action param which points to hook wp_ajax_{action_param} or wp_ajax_nopriv_{action_param} and from there you jump to function from that hooks.
From Codex:
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
$status = $_POST['status'];
}
first you shouldn't write the url by yourself. You could use the localize function to add the url to your javascript file:
wp_enqueue_script('myHandle','pathToJS');
wp_localize_script(
'myHandle',
'ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
After this you can use ajax_obj.ajax_url within your script to receive the url.
Second, did you implement the correct hook?
// Only accessible by logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// Accessible by all visitors
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Best Regards
All seems in order, but still not getting destination populated.
So far I've verified that it can find the PHP and JS files within the plugin I created and even generate the output in XML. That I can see if I let the default <a> tag behavior.
Somehow it blocks where the output is generated.
Thanks
This is for a custom page.
1 - Here is the HTML:
Link to trigger ajax:
$link = admin_url('admin-ajax.php?action=pay_dialog_step1&boo_zone='.$palier['palier']);
'.get_option('_boopass_buybtn_label', '').'
Division to be populated:
<div id="alloconv_popup"></div>
2- PHP code in a plugin directory
add_action("wp_ajax_pay_dialog_step1", "pay_dialog_step1");
// ajax call
function pay_dialog_step1(){
$boo_zone = $_REQUEST['boo_zone'];
$response = new WP_Ajax_Response;
$html = '<div class="bp_entry_wrapper">
<div class="entry normal" >
<div class="alloconv_palier_header" >
<p> Alloconv ' . get_option('alloconv_' . $_REQUEST['boo_zone'] .'_token', '') . ' tokens </p>
</div>';
$html.= get_option('alloconv_' . $_REQUEST['boo_zone'] .'_script', '');
$html.= "</div>";
$html.= "</div>";
$response->add( array(
'data' => 'success',
'supplemental' => array(
'boo_zone' => $boo_zone,
'message' => $html,
),
) );
$response->send();
exit();
}
add_action('init', 'ajax_popup_script' );
function ajax_popup_script() {
wp_register_script( "ajax_popup_script", WP_PLUGIN_URL.'/ajax-popup-paiement/ajax_popup_paiement.js', array('jquery') );
wp_localize_script( 'ajax_popup_script', 'ajaxPaiement', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_popup_script' );
}
3- jquery code on same plugin directory
jQuery(document).ready( function() {
jQuery(".do_popup").click( function(e) {
e.preventDefault();
var link = this;
var boo_zone= jQuery(link).attr("id");
var info = {
action: 'pay_dialog_step1',
boo_zone: boo_zone
};
// Post to the server
jQuery.ajax({
type:"POST",
url:ajaxPaiement.ajaxurl,
data:info,
dataType:html,
success: function(data){
jQuery("#alloconv_popup").html(data);
}
});
});
});
You have to let wp know who can use the ajax calls.
wp_ajax is for the admin section
add_action('wp_ajax_process_ajax_input', 'callBackFunction_Name');
wp_ajax_nopriv is for non admin (users)
add_action('wp_ajax_nopriv_process_ajax_input', 'callBackFunction_Name');
This is the call back function that will then process your ajax call.
function callBackFunction_Name{
$allFields = $_REQUEST;
#todo process input.
}
I finally found what the issue was. Simply, on the ajax call, the data type should be 'xml' instead of 'html.
The WP_Ajax_Response generates an XML file, so one needs to adapt the ajax call accordingly.
I've tried a bunch of different things but I just cannot get AJAX with Wordpress to work. I clearly don't get something but I do not know what it is. The PHP function works fine since I have tested it, it just seemingly isnt getting through to the JS. The idea is that when someone clicks the #subscribe-btn div its updates that users meta, nothing overly sophisticated. Any help on why this isnt working would be great.
This is in my theme's functions.php:
function add_admin_ajax()
{
wp_localize_script( 'add_ajax', 'functionAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add_ajax', get_template_directory_uri().'/assets/js/onLoad.js', 'jquery', true);
}
add_action('template_redirect', 'add_admin_ajax');
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
function subscribe_cat()
{
global $current_user;
if(is_user_logged_in())
{
get_currentuserinfo();
$userid = $current_user->ID;
$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
$subs = get_user_meta($userid, 'user_subscriptions', true);
if(empty($subs))
{
$subs = array();
}
if(!in_array($cat_id, $subs))
{
$subs[] = $cat_id;
update_user_meta($userid, 'user_subscriptions', $subs);
//echo json_encode($subs);
}
}
die();
}
And then the jQuery:
$(document).on("click", "#subscribe-btn", function (e) {
//e.preventDefault();
$('#subscribe-btn').fadeOut(300);
$.ajax({
url: ajaxurl,
data: {action: "subscribe_cat"},
success: function() {
alert("Yay!")
},
error: function() {
alert("BOo!")
}
}); // end ajax call
});
I'm not getting either the success or error message. The div does fade out though that is something i guess. Any help here? Thanks!
EDIT:
I just changed the action identifier in add_action from subscribe to subscribe_cat and changed the ajax url from functionAjax.ajaxurl to simply ajaxurl. Now its responding. However I get the success alert twice, which I do not understand, and it doesn't seem its actually triggering the PHP function, or at least not properly, since I'm not getting the results I get when I simply call the function in PHP whithout ajax. Any ideas here?
One thing for sure you need to do is change the way your action is setup in the WordPress themes functions.php file.
I think this is an issue: wp_ajax_subscribe
This:
add_action( 'wp_ajax_subscribe', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe', 'subscribe_cat' );
should be:
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
The action you set in your javascript needs to match the ending of the first parameter in your wordpress add_action call.
The WordPress documentation
You should pass page info such as query_var as "data" with your ajax function.
frontend page
<?php
$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
?>
<script>
$(document).on("click", "#subscribe-btn", function (e) {
e.preventDefault();
$('#subscribe-btn').fadeOut(300);
$.ajax({
url: ajaxurl,
data: {
action: "subscribe_cat",
catid: "<?php echo $cat_id;?>"
},
success: function(response) {
console.log(response);
},
error: function() {
alert("BOo!")
}
}); // end ajax call
});
</script>
Also in your ajax function you had a condition that will always evaluate to false.
functions.php
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
function subscribe_cat(){
//changed here!!
$cat_id = $_POST['catid'];
if(!$cat_id){
echo 'cat_id is missing';
exit;
} elseif(!is_user_logged_in()) {
echo 'Not logged in!';
exit;
}
$userid = get_current_user_id();
$subs = get_user_meta($userid, 'user_subscriptions', true);
if(empty($subs))
$subs = array();
$subs[] = $cat_id;
update_user_meta($userid, 'user_subscriptions', $subs);
echo json_encode($subs);
exit;
}