Apply Chosen Select Plugin in Wordpress AJAX - javascript

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

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

json not displaying with dataType :'json'

i'm tying to do an ajax get call
i can successfully console.log the result without putting the datatype json in the ajax
dataType: 'json',
when i console.log without it i get
{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}
however i cant display the json data
if i put
dataType: 'json',
my
console.log
is empty
i dont understand where the problem is
$(document).ready(function(){
var username = $("#usernameinfo").text();
$.ajax({
type:"GET",
url: "<?= base_url()?>"+"account/listings/more_user_ads",
data: {"username":username,"pid":"<?=$this->input->get('pid')?>"},
success: function(res){
console.log(res);
}
});
});
php
function more_user_ads(){
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
if($query->num_rows()>0){
foreach($query->result() as $row){
if($post_id != $row->post_id){
$result = array(
'id'=> $row->id,
'post_id'=> $row->post_id,
'post_title'=> $row->post_title,
'image1'=> $row->image1,
'price'=> $row->price,
'price'=> $row->price,
);
$res = json_encode($result);
echo $res;
Add each row to the $result array then echo the json_encode once.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
if($post_id != $row->post_id)
{
$result[] = array(
'id' => $row->id,
'post_id' => $row->post_id,
'post_title' => $row->post_title,
'image1' => $row->image1,
'price' => $row->price,
'price' => $row->price,
);
}
}
}
echo json_encode($result);
}
Actually, you can shorten this a bit by using $query->result_array(); because you won't have to convert an object to an array.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
$rows = $query->result_array();
foreach($rows as $row)
{
if($post_id != $row['post_id'])
{
$result[] = $row;
}
}
}
echo json_encode($result);
}

echo select options according to AJAX call

ive been trying this for the whole day and cant get my head around it. Im retrieving a count from an ajax call called quote.pdfnum which tells me the number of pdfs generated per user. I want to echo quote.pdfnum (number) of options. Im trying to echo in the select at the last table column.
setInterval(function(){
$.ajax({
url: 'poll_requests.php',
type: 'POST',
data: {data:currRequests},
dataType: 'json',
// dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
})
.done(function(response, textStatus, jqXHR) {
// console.log("new Requests "+response.new_quotes);
// console.log("all requests "+response.all_quotes);
var oldRequests = currRequests;
currRequests = response.all_quotes;
var newRequests= response.new_quotes;
if(oldRequests!=currRequests){
if(activeTab!='requests_tab' && newRequests.length>0 && pollRequests>1){
var spanText=Number($('#rbadge').text())+newRequests.length;
$('#rbadge').text(spanText);
}
if(newRequests.length==0 && oldRequests.length==1){
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
$("#rtable tr:first").after("<tr><td colspan='8'>No pending requests at the moment...</td></tr>");
}
if(newRequests.length>0 && oldRequests.length==1){
//and old requests are 0 (-1) remove the first row "no requests at the moment"
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
}
for (var i = 0; i < newRequests.length; i++) {
quote = newRequests[i];
if (activeTab!='requests_tab' && pollRequests>1) {
noty({text: quote.company+' requested a new quote'});
};
// $("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a><a class='approve' href='approve.php?id="+quote.id+"'>Approve</a></td> </tr>");
$("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a></td><td><select name='pdfs' id='pdfs'></select></td> </tr>");
};
}
// console.log('requests length '+newRequests.length);
pollRequests++;
})
.fail(function(error) {
console.log("error"+ error.responseText);
})
.always(function() {
// alert("complete");
});
// },1000000);
},2000);
And this is my poll_requests.php page.
<?php
header('Content-Type: application/json');
$data = $_POST['data'] ;
$new_quotes = array();
$files = array();
$all_quotes = array();
require_once('db_connect.php');
$sql = $db->prepare("SELECT * FROM users, quotes WHERE users.id = quotes.user_id and quotes.status = 'req' ORDER BY quotes.rdate ASC");
if($sql->execute()){
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$files[] = $row;
}
}
foreach ($files as $file):
$quote_id = $file['quote_id'];
$all_quotes[] = $quote_id;
if(!in_array($quote_id, $data)):
$date_time=explode(' ',$file['qdate']);
$insured=$file['insured'];
$status = $file['status'];
$user_id = $file['id'];
$username= $file['username'];
$country = $file['country'];
$company = $file['company'];
$pdfcount = $file['pdfnum'];
$pdf_path="all/$quote_id/$quote_id.pdf";
$new_quotes[] = array('id' => $quote_id,
'user' => $username ,
'country' => $country,
'insured' => $insured,
'status' => $status,
'date' => $date_time[0],
'time' => substr($date_time[1],0,8),
'company' => $company,
'pdfcount' => $pdfcount,
'pdf' => $pdf_path);
endif;
endforeach;
$all_quotes[]=-1;
$data_to_send = array();
$data_to_send['new_quotes'] = $new_quotes;
$data_to_send['all_quotes'] = $all_quotes;
$json_to_send = json_encode($data_to_send);
echo $json_to_send;
?>

How to integrate ajax to Wordpress theme?

I am trying to use ajax in wordpress
I have two files, php and js
this is my php code
combo_check-out.php
function iRange($first, $last, $format = 'm/d/Y' ) {
$dates = array();
$current = strtotime($first);
$i=1;
while( $i <= $last ) {
$dates[] = date($format, $current);
$current = strtotime('+1 day', $current);
$i++;
}
$time = date("m/d/Y",$current);
return $time;
}
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
?>
<select name="check-out" id="check-out-date">
<option value="<?php echo iRange($id, 1, $format = 'm/d/Y' ) ?>">"1 Day (Same Day)"</option>
<option value="<?php echo iRange($id, 2, $format = 'm/d/Y' ) ?>">"2 Days"</option>
<option value="<?php echo iRange($id, 3, $format = 'm/d/Y' ) ?>">"3 Days"</option>
<option value="<?php echo iRange($id, 4, $format = 'm/d/Y' ) ?>">"4 Days"</option>
</select>
<?php}?>
and here it is my js code
combo_checkout_iRange.js
$(document).ready(function() {
$('#loader').hide();
$('#check-in-date').change(function(){
$('#check-out-date-wrap').fadeOut();
$('#loader').show();
$.post("combo_check-out.php", {
parent_id: $('#check-in-date').val(),
}, function(response){
setTimeout("finishAjax('check-out-date-wrap', '"+escape(response)+"')", 400);
});
return false;
});
});
//JQuery to hide Loader and return restults
function finishAjax(id, response){
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function alert_id()
{
if($('#check-out-date').val() == '')
alert('Please select a sub category.');
else
alert($("#check-out-date").val());
return false;
}
they work fine outside wordpress
how to integrate them in wordpress theme
Note: this should work in post type called "meetings"
so this is what i wrote on function.php
add_action("wp_enqueue_scripts", function() {
if (is_single()) {
if (get_post_type() == 'meetings')
{
wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true);
}
}
});
First step
the url you need to hit that is :
<?php echo admin_url( 'admin-ajax.php' ); ?>
now there are couple of method to get this into the js . that is your "ajaxurl"
Second Step
with the url , you need to pass a action like :
url?action=your_ajax_hit
in jquery , it would be like :
$.ajax({
url : ajaxurl+'?action=your_ajax_hit',
type : 'post'
.....
.....
.....
});
Third Step
into the functions.php you can add
add_action("wp_ajax_your_ajax_hit", "your_function_name");
add_action("wp_ajax_nopriv_your_ajax_hit", "your_function_name");
function your_function_name(){
// your code
wp_die();
}
you can see its
wp_ajax_ your_ajax_hit
thats it
please read this : http://codex.wordpress.org/AJAX_in_Plugins

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.

Categories