Wordpress send email with callback and response using Jquery - javascript

Unfortunately I am a beginner in WP code writing and I am trying to implement a custom mail send form in WP whit a response but I have no idea how to do it.
I have the following code in witch "send_carrier_email_callback" should be the e-mail send function:
add_action('wp_ajax_send_carrier_email', 'send_carrier_email_callback');
add_action('wp_ajax_nopriv_send_carrier_email', 'send_carrier_email_callback');
function send_carrier_email_callback(){
global $wpdb;
var_dump($_POST);
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = $_POST['email'];
$subject = $_POST['carriertittle']." állásjelentkezés";
$body = $_POST['massage'];
wp_mail( $to, $subject, $body );
// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
}
function get_carier_ation_callback() {
global $wpdb;
$post_id = $_POST['career'];
$meta = get_post_meta($post_id, "slide_options");
$meta_values =$meta[0];
$args = array (
'p' => $post_id,
'post_type' => array( 'enetix_career' ),
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<script>
jQuery(document).ready(function(){
jQuery('#applybutton').click(function(){
jQuery('#applyform').toggle("slow");
});
jQuery('#carrieremailsend').click(function(){
var career_id = jQuery('#carrierid').val();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var massage = jQuery('#massage').val();
var data = {
action: 'send_carrier_email',
career: career_id,
name: name,
email: email,
massage: massage
}
jQuery.post(ajaxurl, data, function(response) {
});
});
});
In the "jQuery.post(ajaxurl, data, function(response)" I should get a response if the send was successful or not.
Anyone could help me?
Thank you

You need to do something like this. Hope it works for you:
add_action('wp_ajax_send_carrier_email', 'send_carrier_email_callback');
add_action('wp_ajax_nopriv_send_carrier_email', 'send_carrier_email_callback');
function send_carrier_email_callback(){
global $wpdb;
$send_email = false;
$to = $_POST['email'];
$subject = 'Your subject goes here';
$message = $_POST['message'];
$send_mail = wp_mail( $to, $subject, $message );
echo $send_mail; //returns true or false
}
function get_carier_ation_callback() {
global $wpdb;
$post_id = $_POST['career'];
$meta = get_post_meta($post_id, "slide_options");
$meta_values =$meta[0];
$args = array (
'p' => $post_id,
'post_type' => array( 'enetix_career' ),
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<script>
jQuery(document).ready(function(){
jQuery('#applybutton').click(function(){
jQuery('#applyform').toggle("slow");
});
jQuery('#carrieremailsend').click(function(){
var career_id = jQuery('#carrierid').val();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var massage = jQuery('#massage').val();
$.ajax({
type: 'post',
url: ajaxurl,
data: {action: 'send_carrier_email_callback', name: name, email: email, message: message},
success: function(response){
console.log(response); //your response goes here
if(response === true){
//color your div or whatever element green
}else{
//color your div red
}
}
});
});
});

Related

Wordpress favorite system without plugin learning method

Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom

Can I send filtered data with Ajax back to PHP file and write them again on page?

I implemented my Custom Post Type and content is listed on my page in while loop in that way:
$args = array('post_type' => 'studien', 'order' => 'ASC', 'posts_per_page' => 4 );
$loop = new WP_Query($args);
if($loop->have_posts()):
while($loop->have_posts()) : $loop->the_post();?>
<div class="col-md-6">
// data are listed here
</div>
<?php endwhile;
endif;
?>
And on my submit I try to filter data according to some custom taxonomies:
$ = jQuery;
var search = $("#search-studien");
var searchForm = search.find("studien");
$(document).ready(function () {
$('#studien').submit(function (evt) {
event.preventDefault();
var data = {
action: "studien_search",
type: $("#taxonomy-market-type").val(),
};
var html;
$.ajax({
url: ajaxurl,
data: data,
success: function (response) {
if(response)
{
// probably here I need to send filtered data back to PHP file and write them again
}
}
});
})
});
I use custom shortcode and callback() function:
function search_callback()
{
header('Content-Type: application/json;charset=utf-8');
$type = "";
$type = $_GET['type'];
$args = array(
"post_type" => "studien",
"post_per_page" => -1,
"relation" => "AND"
);
if($type != "") {
$args['tax_query'][] = array(
'taxonomy' => 'market',
'field' => 'slug',
'terms' => $type
);
$search_query = new WP_Query($args);
// echo json_encode($search_query);
}
else{
$search_query = new WP_Query( $args );
}
if ( $search_query->have_posts() ) {
$result = array();
while ($search_query->have_posts()) {
$search_query->the_post();
$result[] = array(
"id" => get_the_ID(),
"title" => get_the_title(),
"permalink" => get_permalink(),
);
};
wp_reset_query();
echo json_encode($search_query);
}
else {
// nothing
}
wp_die(); global $argsAjaxFilter;
$argsAjaxFilter = $search_query;
}
As you can see, $search_query represents my filtered data. This is method according to tutorial, but I can`t use response array() ... and best way for me is to send $search_query in some way to PHP file, where I can write my new Custom Post Type data again. Please, someone has advice for me? Is that good proposal?
So the main problem is to be able to send the rendered html to the browser. For that, we're going to need a template so we can reuse it in various places.
// your-theme/studien.php
<div class="studien-wrapper">
<?php
if($wp_query->have_posts()):
while($wp_query->have_posts()) : $wp_query->the_post();
// Do the thing
endwhile;
endif;
?>
</div>
Next, we need to load it whenever is needed. We can do it by using get_template_part. This function will pass some global variables automatically (such as $wp_query) to the template, you can have a look at the source code to learn more. When using it in "ajax mode" we need to capture the output, not send it to the browser (although we could) so we use output buffering. For "normal pages" just omit those calls.
// Set up query args
global $wp_query = new WP_Query($args);
ob_start(); // Capture the output.
get_template_part('studien');
$html_result = ob_get_clean();
And now is a matter of composing the response:
$result['html'] = $html_result;
if (!is_array($type)) {
$type = array($type);
}
$result['query_terms'] = $type;
$json = wp_json_encode($result);
echo $json;
wp_die();
You could also keep track of the search terms on the client side and avoid the last part. Depends on what you need.
To update the page you can do the following in your ajax call:
$.ajax({
url: ajaxurl,
data: data,
success: function (response) {
$('.studien-wrapper').replaceWith(response.html);
// Update search terms, etc
}
});

Ajax jQuery on success if statement double json_encode return underfined value

I trying to get $comments_id,$comments_timestamp, $user_firstname, $user_lastname values and pass back to ajax, but in the if statement was execute only one object array which is ['successful-submit-comment'] = true;.
Ajax
$.ajax({
type:'post',
url:'getcomment_detail.php',
data:{comment_id: comment_id,user_desc:user_desc},
cache:false,
dataType:'json',
success: function (data){
console.log(data);
var ttes1 = data.comments_timestamp;
alert(ttes1);
}
});
getcomment_detail.php :
$u_id = $_SESSION['u_id'];
$submit_comment_status = array();
if($sql = "INSERT INTO comments (post_id, user_id, user_desc) VALUES ('$comment_id','$u_id','$user_desc')"){
mysqli_query($conn,$sql);
mysqli_close($conn);
$get_comment_user_detail = "SELECT comments.id, comments.timestamp, user.firstname, user.lastname FROM comments INNER JOIN user ON user.id = comments.user_id WHERE user.id = $u_id ORDER BY comments.id DESC LIMIT 1";
if($stmt = $conn->prepare($get_comment_user_detail)) {
$stmt->execute();
$stmt->bind_result($comments_id, $comments_timestamp, $user_firstname, $user_lastname);
while ($stmt->fetch()) {
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
}
$stmt->close();
}
$submit_comment_status['successful-submit-comment'] = true;
header('Content-Type: application/json');
echo json_encode($submit_comment_status);
}
Console return value:
Alert return value:
Undefined
Why don't you just put it into the array and return it all as a json file?
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname,
'successful-submit-comment' => true
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
and in your ajax you just get the value like
console.log(data['successful-submit-comment']);

Wordpress - Targeting Individual POST, rather than POST Type. AJAX/PHP

I am trying to load the individual post information on click into the page when clicking the post title. I have managed to get my script to loop through the titles in the post array and on click load the post titles once more into a div. I want this to load the individual post information instead on click.
PHP Post Array Functions -
add_action( "wp_ajax_success_stories", "sa_get_paginated_posts" );
add_action( "wp_ajax_nopriv_success_stories", "sa_get_paginated_posts" );
function sa_get_paginated_posts(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'success-stories',
'orderby' => 'post_date',
'order' => 'DESC'
);
$the_query = new WP_Query( $args );
$queryitems = $the_query->get_posts();
$alldata = array();
if ($queryitems){
foreach ($queryitems as $query_item){
$success_story = array();
$success_story["ID"] = $query_item->ID;
$success_story["title"] = $query_item->post_title;
$alldata[] = $success_story;
}
}
$encoded_data = json_encode($alldata);
echo $encoded_data;
die();
}
function sa_get_posts($post_amount, $post_type){
$args = array(
'posts_per_page' => $post_amount,
'post_type' => $post_type,
'offset' => 0,
'orderby' => 'post_date',
'order' => 'ASC'
);
Using this function to loop through -
<? if ($success_stories): //success story posts ?>
<ul class="small-block-grid-3">
<? foreach ($success_stories as $success_story):
$title = $success_story->post_title; ?>
<li><a data-id="<? echo $success_story->ID; ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>
<? endforeach; ?>
</ul>
<div id="success-list"></div>
<a class="success-close" href="#" title="">CLOSE</a>
<? endif; ?>
Javascript/ AJAX Call
var $json_response_box = $("#success-list");
function get_ajax_success_posts() {
//this line gets the id attribute from the link
var current_story = $(this).attr("data-id");
console.log(current_story);
jQuery.ajax({
type: "GET",
url: "WORDPRESSDIRECTORY/admin-ajax.php",
cache: true,
data: {
action: "success_stories"
},
dataType: "JSON",
success: function(data) {
var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
var success_id = data[i].ID;
var success_title = data[i].title;
console.log(success_id);
story = '<ul>';
story += '<li>';
story += success_title;
story += '</li>';
story += '</ul>';
$json_response_box.append(story).fadeIn(1000);
}
},
error: function(errorThrown) {
console.log("fail-posts");
}
});
}
Appreciate your suggestions,
D
If I understand your question correctly, you should just add another php function and AJAX call, to get the post on click, something like this (I also added nonce to add some secutiry, it's always a good idea to add that to your ajax calls)
HTML:
<li><a data-id="<? echo $success_story->ID; ?>" data-nonce="<?php wp_create_nonce('get_post'.$success_story->ID); ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>
PHP:
add_action( "wp_ajax_sa_get_post", "sa_get_post" );
add_action( "wp_ajax_nopriv_sa_get_post", "sa_get_post" );
function sa_get_post(){
if ( ! wp_verify_nonce( $nonce, 'get_post_'.$POST['id'] ) ) {
// This nonce is not valid.
$response['status'] = 'fail';
} else {
// The nonce was valid.
$post = get_post($POST['id']);
$response['status'] = 'success';
$response['post'] = $post;
}
echo json_encode($response);
exit(); // this is needed, as otherwise the AJAX returns an extra 0
}
JS:
$('.success-extra').on('click', function () {
jQuery.ajax({
type: "POST",
url: "WORDPRESSDIRECTORY/admin-ajax.php",
cache: false,
data: {
action: "sa_get_post",
id: $(this).attr('data-id'),
nonce: $(this).attr('data-nonce')
},
success: function(data) {
var result = $.parseJSON(data);
if (result.status != 'success') {
// display error messago or something
} else {
// do whatever you want with your result.post
}
}
})
Hope this helps.

Apply Chosen Select Plugin in Wordpress AJAX

P.S. This question is long as there's lot of code. Thank you for your patience and time. I appreciate it.
I am using ultimate wp query search filter plugin on my wordpress site. I would like to use chosen plugin instead of default select boxes. The select boxes already on the page are working perfectly with this code.
(function($){
$(".first-ddwn, .second-ddwn, .third-ddwn, .main-ddwn, .posts_ajax select").chosen({
no_results_text: "Oops, nothing found!",
width: "50%"
});
})(jQuery);
I have changed the result html for AJAX search as mentioned by the plugin author so that I get a dropdown of result posts.
add_filter('uwpqsf_result_tempt', 'customize_output', '', 4);
function customize_output($results , $arg, $id, $getdata ){
// The Query
global $post;
$apiclass = new uwpqsfprocess();
$query = new WP_Query( $arg );
ob_start(); $result = '';?>
<form action="<? bloginfo('url'); ?>" method="get"><?php
echo '<select name="page_id" id="page_id">';
echo '<option value="">Select</option>';
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<option value="<? echo $post->ID; ?>"><?php echo the_title(); ?></option>
<?php }
echo '</select>';
echo '<input type="submit" name="submit" value="view" />';
echo '</form>';
} else {
echo 'no post found';
}
/* Restore original Post Data */
wp_reset_postdata();
$results = ob_get_clean();
return $results;
}
However, chosen doesn't get applied to this result dropdown. I have tried the option of using settimeout after the AJAX call as mentioned http://davidwalsh.name/jquery-chosen#comment-29299 but it didn't work. maybe I did it wrong. Also when I run it after ajax call like below, chosen does get applied to the select but is all broken.
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
$(".content select").chosen();
}
});
This is what I get
This is plugin's uwpqsfscript.js file
jQuery(document).ready(function($) {
$('body').on('click','.usearchbtn', function(e) {
process_data($(this));
return false;
});
$('body').on('click','.upagievent', function(e) {
var pagenumber = $(this).attr('id');
var formid = $('#curuform').val();
upagi_ajax(pagenumber, formid);
return false;
});
$('body').on('keypress','.uwpqsftext',function(e) {
if(e.keyCode == 13){
e.preventDefault();
process_data($(this));
}
});
window.process_data = function ($obj) {
var ajxdiv = $obj.closest("form").find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $obj.closest("form").serialize();
var pagenum = '1';
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
}
});
}
window.upagi_ajax = function (pagenum, formid) {
var ajxdiv = $(''+formid+'').find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $(''+formid+'').serialize();
jQuery.ajax({
type: 'POST',
url: ajax.url,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty(); res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
//res.container.find(res.loader).remove();
}
});
}
$('body').on('click', '.chktaxoall,.chkcmfall',function () {
$(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
});
});//end of script
And some relevant code (maybe?) from uwpqsf-process-class.php
//front ajax
add_action( 'wp_ajax_nopriv_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'wp_ajax_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'pre_get_posts', array($this ,'uwpqsf_search_query'),1000);
}
function uwpqsf_ajax(){
$postdata =parse_str($_POST['getdata'], $getdata);
$taxo = (isset($getdata['taxo']) && !empty($getdata['taxo'])) ? $getdata['taxo'] : null;
$cmf = (isset($getdata['cmf']) && !empty($getdata['cmf'])) ? $getdata['cmf'] : null;
$formid = $getdata['uformid'];
$nonce = $getdata['unonce'];
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
if(isset($formid) && wp_verify_nonce($nonce, 'uwpsfsearch')){
$id = absint($formid);
$options = get_post_meta($id, 'uwpqsf-option', true);
$cpts = get_post_meta($id, 'uwpqsf-cpt', true);
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
$default_number = get_option('posts_per_page');
$cpt = !empty($cpts) ? $cpts : 'any';
$ordermeta = !empty($options[0]['smetekey']) ? $options[0]['smetekey'] : null;
$ordertype = (!empty($options[0]['otype']) ) ? $options[0]['otype'] : null;
$order = !empty($options[0]['sorder']) ? $options[0]['sorder'] : null;
$number = !empty($options[0]['resultc']) ? $options[0]['resultc'] : $default_number;
$keyword = !empty($getdata['skeyword']) ? sanitize_text_field($getdata['skeyword']) : null;
$get_tax = $this->get_uwqsf_taxo($id, $taxo);
$get_meta = $this->get_uwqsf_cmf($id, $cmf);
if($options[0]['snf'] != '1' && !empty($keyword)){
$get_tax = $get_meta = null;
}
$ordermeta = apply_filters('uwpqsf_ometa_query',$ordermeta,$getdata,$id);
$ordervalue = apply_filters('uwpqsf_ometa_type',$ordertype,$getdata,$id);
$order = apply_filters('uwpqsf_order_query',$order,$getdata,$id);
$number = apply_filters('uwpqsf_pnum_query',$number,$getdata,$id);
$args = array(
'post_type' => $cpt,
'post_status' => 'publish',
'meta_key'=> $ordermeta,
'orderby' => $ordertype,
'order' => $order,
'paged'=> $pagenumber,
'posts_per_page' => $number,
'meta_query' => $get_meta,
'tax_query' => $get_tax,
's' => esc_html($keyword),
);
$arg = apply_filters( 'uwpqsf_query_args', $args, $id,$getdata);
$results = $this->uajax_result($arg, $id,$pagenumber,$getdata);
$result = apply_filters( 'uwpqsf_result_tempt',$results , $arg, $id, $getdata );
echo $result;
}else{ echo 'There is error here';}
die;
}//end ajax
function uajax_result($arg, $id,$pagenumber,$getdata){
$query = new WP_Query( $arg );
$html = '';
//print_r($query); // The Loop
if ( $query->have_posts() ) {
$html .= '<h1>'.__('Search Results :', 'UWPQSF' ).'</h1>';
while ( $query->have_posts() ) {
$query->the_post();global $post;
$html .= '<article><header class="entry-header">'.get_the_post_thumbnail().'';
$html .= '<h1 class="entry-title">'.get_the_title().'</h1>';
$html .= '</header>';
$html .= '<div class="entry-summary">'.get_the_excerpt().'</div></article>';
}
$html .= $this->ajax_pagination($pagenumber,$query->max_num_pages, 4, $id,$getdata);
} else {
$html .= __( 'Nothing Found', 'UWPQSF' );
}
/* Restore original Post Data */
wp_reset_postdata();
return $html;
}//end result
I have been searching for days and have tried many things to make this work. I have no knowledge of jquery,so maybe someone will help me out.
Many Thanks

Categories