Category: Ajax

WordPress search Post(news) with ajax

js code


/* All filter news and pagination*/
jQuery('.news-filter .categoryCheck').on( 'change' , function() {
if(!jQuery(this).val()){
jQuery('.news-filter .categoryCheck').prop( "checked", false );
}
load_news_list(0,1);
});

jQuery('.search-btn').on( 'click' , function() {
load_news_list(0,1);
});
jQuery('#srch_keyword').on('keypress', function(e){
if(e.keyCode == '13'){
e.preventDefault();
load_news_list(0,1);
}
});
jQuery('.pagination').on( 'click', '.page-numbers', function( event ) {
event.preventDefault();
page = find_page_number(jQuery(this));
var post_length = jQuery( '.news-div' ).length;
load_news_list( post_length, page);
});

 

/* load news list */
function load_news_list(post_length, page) {

var news_cats = jQuery('.categoryCheck:checked').map(function() {return this.value;}).get().join(',');
var year = ( jQuery( '#year' ).length > 0 ) ? jQuery( '#year' ).val() : '';
var monthnum = ( jQuery( '#monthnum' ).length > 0 ) ? jQuery( '#monthnum' ).val() : '';
var search_val = jQuery('#srch_keyword').val();
// jQuery( '.clear-all' ).css( 'display' , 'none' );
if( news_cats.length > 0 ) {
jQuery( '.clear-all' ).css( 'display' , 'inline-block' );
}

jQuery.ajax({
type: "POST",
url: adminurl,
data: { action : 'load_news', news_cats: news_cats, post_length : post_length, year: year, monthnum: monthnum ,search:search_val, page: page},
success: function (result){
var responseData = JSON.parse(result);
jQuery( '.load-more-news' ).remove();
jQuery( '.news-listing' ).empty();
jQuery( '.news-listing' ).append(responseData.news);
jQuery( '.pagination' ).empty()
jQuery( '.pagination' ).append(responseData.pagination);
},
error:function(){
alert("Error: There is some issue please try again.");
},
beforeSend:function(){
jQuery( '.load-result' ).css( 'display' , 'block' );
},
complete: function () {
jQuery( '.load-result' ).css( 'display' , 'none' );
}
});
}

 

WordPress code


add_action( 'wp_ajax_nopriv_load_news', 'load_news' );
add_action( 'wp_ajax_load_news', 'load_news' );
function load_news() {
$per_page = 12;
$paged = ( isset($_POST['page']) ) ? $_POST['page'] : 1 ;
$offset = (( $paged - 1 ) * $per_page);
/* if( !empty( $_POST['post_length'] ) ) { */
$post_length = $_POST['post_length'];
//$offset = $post_length;
$nextOffset = $offset + $per_page;
/* } */
$result = '';

$pagination = '';
$newsList = getNewsArray( $offset , $per_page , $_POST );

$result = '<div class="col-sm-12"><header class="page-header">';
$result .= '<h2 class="page-title">Sorry, it seems that we didn&rsquo;t find any results</h2>';
$result .= '</header>';
$result .= '<div class="page-content">';
$result .= '<p>Please try the search function at the top of the page to see if you can find what you&rsquo;re looking for</p>';
$result .= '</div></div>';
if ( $newsList->have_posts() ) {
$result = '';
while ( $newsList->have_posts() ) { $newsList->the_post();
$result .= post_html( $post->ID );
}
}

if($newsList->max_num_pages > 0){
$big = 999999999;
$pagination = paginate_links( array(
'type' => 'plain',
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $newsList->max_num_pages,
'prev_next' => true,
'prev_text' => 'Prev',
'next_text' => 'Next',
) );
//$pagination .= football_pagination($newsList->max_num_pages);

} else {
$result .= '<div class="no-more-news"></div>';
}

$data['news'] = $result;
$data['pagination'] = $pagination;
echo json_encode( $data );

die();
}

&nbsp;
function getNewsArray( $offset , $per_page , $newsFilter ) {

$argsNews = array('post_type' => 'post', 'post_status'=> 'publish' , 'posts_per_page' => $per_page , 'offset' => $offset, 'order' => 'desc', 'orderby' => 'date' );

if( !empty($newsFilter['news_cats']) ) {
$cats = explode( ',' , $newsFilter['news_cats'] );
$argsNews['category__in'] = $cats;
}
if(!empty($newsFilter['year'])){
$argsNews['year'] = $newsFilter['year'];
}
if(!empty($newsFilter['monthnum'])){
$argsNews['monthnum'] = $newsFilter['monthnum'];
}
if(!empty($newsFilter['search'])){
$argsNews['s'] = $newsFilter['search'];
}
$newsList = new WP_Query( $argsNews );

return $newsList;
}

 

 

jQuery selector after dom change

in jQuery some time we can’t get default event[selector] as like “click”,”change”,’focus’ etc. So in bellow snippet we can easily bind event.


/******/
/* Syntax of jquery selector.
/******/
jQuery(selector).live(events, data, handler);                // jQuery 1.3+  
jQuery(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+  
jQuery(document).on(events, selector, data, handler);        // jQuery 1.7+  


/******/
/* jQuery default selector.
/******/
jQuery('.btnAction').click(function(){
	// Do something
});


/******/ 
/* Dynamic content load after some time not bind default jQuery event thane after used those three events.
/******/
jQuery(document).delegate('.btnAction','click',function(e){
	// Do something
});

// jQuery 1.3+  
jQuery('.btnAction').live('click',function(){
	// Do something
});

// jQuery 1.7+  
jQuery('.btnAction').on('click',function(){
	// Do something
});

jQuery(document).on('click',".btnAction", function(){
	// Do something
});

WordPress Ajax search

Live search in WP post using Ajax. to change textbox values as change data.

 

Step => 1 Html Form as like as you need.



<div class="search-column">


<form method="post" action="javascript:void(0);" name="search-form">
<input type="search" placeholder="<?php _e('Search','medium') ?>" autofocus class="pop-search">
</form>





<div id="search_result_form">


<div id="search_text_result"></div>




<div class="row">


<div class="" id="search_result">

</div>


</div>


</div>


</div>



Step => 2 jQuery and Ajax code in JavaScript file.
jQuery('.pop-search').keyup(function(e) {
        jQuery('#search_result_form').css('display','block');
        var text = jQuery('.pop-search').val();
        jQuery('#search_text_result').html('Results for "'+text+'"');
        jQuery.ajax({
                type: "POST",
                url: admin_url,
                dataType:"json",
                data: { 
                    action: 'data_search_ajax',
                    text: text,
                },
                cache: false,
                success: function(data){                    
                    if(data['data_result']==''){
                        jQuery('#search_result').hide();                        
                    }
                    else{
                        jQuery('#search_result').css('display','block');
                        jQuery('#search_result').html(data['data_result']);                            
                    }
                }
        });
    });

Step => 3 Call Ajax using jQuery in WordPress function.
/* Custom search */
function data_search_ajax(){	
	$testdomin_keyword = $_POST['text'];
	$testdomin_args_search = array(
		's'	=>	$testdomin_keyword,
		'post_status' => 'publish',
		'post_type'	=>	'post',
		'post_per_page'	=>	8
	);
	$testdomin_query = new WP_Query($testdomin_args_search);
	$testdomin_result='';	
	if($testdomin_query->have_posts()){		
		while($testdomin_query->have_posts()){
			$testdomin_query->the_post();			
                        $testdomin_featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'medium-blog-small',0 );
			$testdomin_result .= '
<div class="col-md-3 search-box" >';
                        if(!empty($testdomin_featured_image))
                        $testdomin_result .= '<a href="'.get_permalink(get_the_ID()).'"><img class="img-responsive" src="'.esc_url($testdomin_featured_image[0]).'" alt="'.esc_attr(get_the_title()).'"></a>';
			$testdomin_result .= '
<div class="image-sub"><a href="'.get_permalink(get_the_ID()).'">'.get_the_title().'</a></div>


<div class="post-arthur"><a class="privacy" href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">'.get_the_author().'</a></div>

			  </div>

';
		}
	}
	else
		$testdomin_result = _e('Not found','textdomin');
		
	echo json_encode(array("data_result"=>$testdomin_result));
	die;
}
add_action('wp_ajax_nopriv_data_search_ajax', 'data_search_ajax');
add_action('wp_ajax_data_search_ajax', 'data_search_ajax');

PHP Ajax inline edit textbox

Inline Edit MySQL table field using jQuery Ajax and PHP.

Step => 1 HTML and PHP code

<td class="task"><a class="inline_edit" data-feedback_id="<?=$row['id'];?>" href="javascript:void(0);"><?=$row['task_name'];?></a>
        <input type="text" data-data_id="<?=$row['id'];?>" data-fieldname="laci_task" value="<?=$row['task_name'];?>" class="t_inline_edit textbox display0" /> 
</td>

Step => 2 jQuery and Ajax code in .js file.

jQuery(document).ready(function(e) {
    /*****/
    /* Inline Edit save field 
    /****/
    jQuery('.t_inline_edit').bind('blur keypress',function(e){
    
    var $this = jQuery(this);
        
    if(e.keyCode === 13 || e.keyCode === 9 || e.type === 'blur'){
        
        var field_id = jQuery(this).data('data_id');
        
        // field_name to fiend table name
        var field_name = jQuery(this).data('fieldname');        
        var field_value = jQuery(this).val();
        
        // send data 
        var price_data = {
            'function_name':'inline_edit',
            'field_name':field_name, // field_name to fiend table name
            'field_where':field_id,    // field_where to set set sql condition        
            'field_value':field_value
        };
        
        
        jQuery.ajax({
            url: 'ajax-file/ajax.php',
            type: 'POST',
            dataType: "json",
            data: price_data,
            success: function(data){
                //called when successful                
                if(data['message'] == 'success'){
                    $this.closest('td').find('a').text(data['values']['field_value']).show();
                    $this.closest('td').find('input').hide();                    
                    
                }else{
                    //location.reload();
                }
            },
            error: function(e){
                //called when there is an error
                console.log(e.message);
            }            
        });            
    }
    });
});
Step => 3 call Ajax in PHP file using condition in PHP file.
    /****/
    /* Edit inline
    /****/
    if(isset($_POST['function_name']) && $_POST['function_name'] == 'inline_edit' )
    {
        
        if($_POST['field_name'] == 'laci_feedback'){
            $table_name = 'laci_task';
            $field_name = 'feedback';
            $field_where = 'id';
        }
        elseif($_POST['field_name'] == 'laci_task'){
            $table_name = 'laci_task';
            $field_name = 'task_name';
            $field_where = 'id';
        }
        else{
            $return = array('result' => 'Opps !! Geting some Error.');
            echo json_encode($return);
            die;
        }
        
        $sql = "UPDATE $table_name SET
            $field_name = '".$_POST['field_value']."'
            WHERE $field_where = ".$_POST['field_where']."";
            
        //echo $sql;
        $res = mysql_query($sql);
        
        
        $return_data = array(
            'message' => 'success',
            'values' => array(
                'field_value' => $_POST['field_value']                
            ),
        );
        $return = $return_data;        
    }
    

    echo json_encode($return);
    die;