How to get data from wordpress ajax search form? - ajax

My form html code, where i set action and the attribute name.
<div class="search_form">
<form action="<?php esc_url( home_url( '/' ) ); ?>" method="POST">
<input type="text" name="s" value="<?php get_search_query(); ?>" placeholder="Search...">
<input type="submit" value="Send">
</form>
</div>
I use localize scripts to connect ajax-search.
wp_enqueue_script( 'wc-estore-ajax-search-js', get_template_directory_uri() . '/assets/js/ajax-search.js', array( 'jquery' ), _S_VERSION, true );
wp_localize_script( 'wc-estore-ajax-search-js', 'search_form', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'search-nonce' )
) );
In ajax-search got nonce, set action and set url.
jQuery(function ($) {
$('.search_form input[name="s"]').on('keyup', function () {
let search = $('.search_form input[name="s"]').val();
if (search.length < 4) {
return false;
}
let data = {
s: search,
action: 'search_action',
nonce: search_form.nonce
};
$.ajax({
url: search_form.url,
data: data,
type: 'POST',
dataType: 'json',
beforeSend: function (xhr) {
},
success: function (data) {
console.log(data);
}
});
});
});
And in functions.php i want to see, what is in $_POST.
The action is the same as in the search-ajax.js.
add_action( 'wp_ajax_search_action', 'esp_search_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_search_action', 'esp_search_ajax_action_callback' );
function esp_search_ajax_action_callback() {
/**
* Проверяем нонсе из массива пости и из wp_localize script
*/
if(!wp_verify_nonce($_POST['nonce'], 'search-nonce')){
wp_die('Данные пришли с левого адреса');
}
$_POST = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
$args = [
'post_type' => ['post', 'product'],
'post_status' => 'public',
's' => $_POST['s'],
];
$query_ajax = new WP_Query($args);
?>
<?php if($query_ajax->have_posts()): ?>
<?php while($query_ajax->have_posts()): ?>
<?php $query_ajax->the_post(); ?>
<h3 class="title-search"><?php the_title(); ?></h3>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php
}
But the console is clear?
Where is my mistake?
Thanks for help.

Looks like you have a few things going on. Try these:
dataType is the type of data you're expecting back. You're not passing valid JSON back, so it is failing with a parse error (i.e. no success, no console.log).
vardump probably should be var_dump unless you've defined it elsewhere. If not, that's probably causing an error and sending back the error string (which again would not be valid JSON)
Although not necessarily the issue you're asking about, but you should also finish your callback with wp_die(); and pass whatever parameters you need for your situation.
If you want, while you're testing you can switch dataType to html.
You can also add in error (to see what the error is) and complete (to see that it actually came back) callbacks.
And just to be safe, you might want to filter your $_POST data with something like this:
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
or whatever filters fit your situation.

Related

Woocommerce mini-cart ajax apply coupon

I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.
functions:
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
Input:
<?php if (empty (WC()->cart->get_coupons())): ?>
<span id="coupon-form">
<?php if ( wc_coupons_enabled() ) { ?>
<form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
<?php } else { ?>
<form id="apply-promo-code" class="widget_shopping_cart__coupon">
<?php } ?>
<label id="promo-code" for="coupon-code">Promo Code:</label>
<input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
<button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
<?php do_action( 'woocommerce_cart_coupon' ); ?>
<?php do_action( 'woocommerce_cart_actions' ); ?>
</form>
<?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>
<?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
<?php wc_cart_totals_coupon_html( $coupon ); ?>
</span>
<?php endforeach; ?>
jQuery:
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.
function apply_coupon_code(){
$coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
WC()->cart->apply_coupon($coupon_code);
ob_start();
woocommerce_mini_cart();
$cart_html = ob_get_clean();
return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.
Now you need to tell jQuery that you're expecting HTML back from the server...
jQuery(document).on('click', 'button#minicart-apply-button', function() {
var coupon = jQuery( 'input#minicart-coupon' ).val();
var button = ( this );
var data = {
action: "apply_coupon_code",
coupon_code: "coupon"
};
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log(response);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...
success: function (response) {
console.log(response);
jQuery('.mini-cart-wrapper').html(response);
},

AJAX Search returns "You do not have sufficient permissions to access this page" on non-admin user

I have this demo website that I'm making:
https://theme.artware.gr/
The problem I am facing is on the search functionality. You can click on the right/top side search to see the issue. When I am logged-in as admin, the search works fine, but when I view the page as a guest I get the error: "You do not have sufficient permissions to access this page".
This is my code so far:
// AJAX Search (no WooCommerce)
if ( !class_exists( 'WooCommerce' ) ) {
function simple_search_scripts(){
wp_enqueue_script( 'simple_search', get_stylesheet_directory_uri() . '/js/search.js', array(), '1.0.0', true);
wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') ));
}
// Create shortcode
function simple_search(){
simple_search_scripts(); ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="<?php _e('Αναζήτηση...'); ?>" />
<div id="datafetch"></div>
<?php
}
add_shortcode('simple_search', 'simple_search');
// Fetch data
function simple_search_callback(){
$the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_GET['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();
$myquery = esc_attr( $_GET['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) { ?>
<div class="result-sin">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); ?>
<div class="result-sin-img">
<?php if ($image) { ?>
<img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" />
<?php } ?>
</div>
<div class="result-sin-tit"><?php the_title();?></div>
<div class="result-sin-txt"><?php the_excerpt();?></div>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
add_action('wp_ajax_simple_search', 'simple_search_callback' );
add_action('wp_ajax_nopriv_simple_search', 'simple_search_callback' );
}
And the search.js:
function fetch(){
jQuery.ajax({
async: true,
url: myAjax.ajaxurl,
type: 'GET',
data: {
action: 'simple_search',
keyword: jQuery('#keyword').val(),
nonce: myAjax.nonce
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
And on the header, I simply call a shortcode [simple_search] . Everything post I read on SO said that the wp_ajax_nopriv_ACTION was missing. But I already have that.
UPDATE
I tried using method GET, that didn't work. I also used: wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') )); to better enqueue the admin-ajax.php, that didn't work either.
Somewhere In my theme I had require_once('file.php') that had the line below:
if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); }
When I removed this, the problem was fixed.

How to get Advanced Custom Fields values with Ajax in Wordpress

I'm trying to do a WP_query on a custom-post-type but for some reason I cannot get the values from the custom-field-types of these posts.
Here is what I got so far (functions.php)
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
}
And in my JS file have the following:
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases"
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
Can someone tell me what I'm doing wrong?
I also tried to do:
<?php the_field('case_picture'); ?>
but with no luck? what am I missing?
add_action() should be outside your custom function. Try this instead.
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
}
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
you can use this logic by storing the field as a hidden value and pass in ajax through js
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
<input type="hidden" id="hidden" name="hidden_field" value="<?= get_field('case_picture'); ?>"> // store the value
</div>
</a>
<?php }
}
die();
Now get the data in jquery and pass through ajax
<script>
var hidden=//Grab data here.
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases",
image:hidden, // Pass the data
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
</script>
and use the data in ajax called
function fetch_cases()
{
$image=$_POST['image'];
}
get_field method has 2nd parameter which is post ID, pass this and check. It should work.
$post_id = $post->ID;
$value = get_field( 'case_picture', $post_id );

Cakephp ajax insert without using cake ajaxhelper

I am trying to add data in cakephp by ajax without using ajax helper.Here insertion is working fine but problem is after insert data I have failed to see the success massage.Here is my effort.
<script>
$(document).ready(function(){
$('#submit').click(function(){
x=$("#rform").serializeArray();
$.post($("#rform").attr("action"),
x,
function(data)
{
$("#success").html(data);
$("#success").fadeIn();
$("#success").fadeOut(2800);
$("input").val('');
});
$("#rform").submit(function(){
return false;
});
});
});
</script>
Here is the add.ctp code
<?php
echo $this->Form->create('Info',array(
'id' => 'rform'
)); ?>
<fieldset>
<legend><?php echo __('Add Info'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
?>
</fieldset>
<?php
$options = array
(
'label' => 'Add',
'value' => 'Add',
'id' => 'submit'
);
echo $this->Form->end($options);
?>
</div>
<div style="color:green;" id="success">
</div>
Here after add it is repeating insertion page again in bellow.Here I need to show only success massage.If I remove $("#success").html(data); nothing is happening but after insert button name making disappear.How can I add success massage in here ?
I have solved it by little bit change
$("#success").html(data);
to
$("#success").html("Insert Success");
and here I have changed input button tag, I have use direct button here
<button id="submit">Submit </button>

Query vars in url (wordpress) work fine when page loaded directly, but fail on ajax

I've a little issue, and I couldn't find anything about it... I'm in deadlock.
So I've wp page that contains normal loop, if I call this file directly in browser all works fine, and I can even use query-vars such as: http://domain.com/blog/wp-content/themes/wovies-bones/getmovies.php?actor=x And it works fine, I get single post that has custom taxonomy actor = x.
But when I try to load same using ajax, it behaves differently and ignoring my get request returns all posts...
Any ideas what is happening?
ajax-jquery part:
$.ajax({
url: templatePath + "getmovies.php",
type: "GET",
data: filters_get,
cache: false,
success: function (data){
console.dir(data);
}
});
And php part:
/* Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
?>
<div id="container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="movie">
<a href="<?php the_permalink() ?>">
<?php
if (has_post_thumbnail()) {the_post_thumbnail('homepage-preview');}
else {echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/default-poster.jpg" />';}
?>
<p class="comments"><?php comments_number('0 review','1 review','% reviews'); ?></p>
<div class="description">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</div>
</a>
</div>
<?php endwhile; else: ?>
<!-- No movies found -->
<?php endif; ?>
</div><!-- End #container -->
filters_get looks like this: ?actor=x&
This way, you just load WordPress and run your own PHP file. Basicaly, I think you should redefine your WP_Query like this :
/*Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
global $wp_query;
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$wp_query = new WP_Query($args);
// Your template stuff
And if you're using AJAX to get your posts, you'd better use a hooked function as it is described in WordPress Codex :
add_action('wp_ajax_get_my_cpt', 'get_my_cpt');
add_action('wp_ajax_nopriv_get_my_cptn', 'get_my_cpt');
function get_my_cpt() {
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$cpts = get_posts($args);
if(empty($cpts)) {
_e('No custom post to show');
exit;
}
foreach($cpts as $cpt) {
// Do you stuff to display your custom posts
}
}
Then you will have to use this kind of url in your AJAX call : http://www.domain.tld/wp-admin/admin-ajax.php?action=get_my_cpt&my_tax=keyword

Resources