stop page reloading when using ajax - ajax

I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?

Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});

Related

Woocommerce ajax return empty shipping packages

Am trying to get the shipping packages with ajax but its always returning empty value.
same issue while trying to call get the zones with: WC_Shipping_Zones::get_zones();
am using the same code in woocommerce_checkout_before_order_review and its working without any issue!
function jsforwp_add_like() {
check_ajax_referer( 'jsforwp_likes_nonce' );
$packages = WC()->shipping->get_packages();
if(empty($packages)){
$check = 'empty';
}else{
$check = $packages;
}
$success = true;
if( true == $success ) {
$response['type'] = 'success';
$response['zone'] = $check;
}
$response = json_encode( $response );
echo $response ;
die();
}
add_action( 'wp_ajax_jsforwp_add_like', 'jsforwp_add_like' );
add_action( 'wp_ajax_nopriv_jsforwp_add_like', 'jsforwp_add_like' );
My javascript
add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){
$( document.body ).on( 'updated_checkout', function(){
$.ajax({
type : 'post',
dataType : 'json',
url : jsforwp_globals.ajax_url,
data : {
action: 'jsforwp_add_like',
_ajax_nonce: jsforwp_globals.nonce
},
success: function( response ) {
if( 'success' == response.type ) {
console.log( response );
}
else {
console.log( 'Something went wrong, try logging in!' );
}
}
});
} );
} )( jQuery );
</script>
<?php
}
returned value
{type: "success", zone: "empty"}

Get post meta in the Ajax not working in Wordpress

I am doing an Ajax call and return the value. The post id is coming. But when i tried with this code, It is return blank
function visa_status() {
$postid = $_POST['appid'];
// args
$args = array(
'numberposts' => 1,
'post_type' => 'cpt_15',
'meta_key' => 'application_number',
'meta_value' => $postid
);
$metaarry = array();
// query
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$posti = get_the_ID();
endwhile;
//echo $posti;
echo get_post_meta( $posti, 'given_name');
exit();
}
In the above code, $posti is coming. But get_post_meta() is not working.
This is my JS part
onStepChanging: function (event, currentIndex, newIndex) {
if ( newIndex === 1 ) {
jQuery('.wizard > .steps ul').addClass('step-2');
appId = jQuery('#appid').val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action': 'visa_status',
'appid': appId,
},
success: function (msg) {
console.log(msg);
}
});
} else {
jQuery('.wizard > .steps ul').removeClass('step-2');
}
if ( newIndex === 2 ) {
jQuery('.wizard > .steps ul').addClass('step-3');
} else {
jQuery('.wizard > .steps ul').removeClass('step-3');
}
return true;
},
Is there any mistake i have done. Please help me in this.
Try this
$given_name = get_post_meta( $posti, 'given_name', true );
echo $given_name;
OR Try this
echo get_post_meta( $posti, 'given_name', true );
Check here what get_post_meta function returns based on 3rd parameter.

Code igniter validation- Ajax, error:function work while validation->run is true

Hi I try to make validation form with ajax. When Textbox is empty, There is no problem everything works fine and give right errors. But when I fill in form Ajax else is not working and it goes to error:function . Please could you help!
When I enable dataType:"JSON",
I see output
false
Basvuru:1379 {isim: " İsim Zorunludur!", soyad: " Soyad Zorunludur!", emailadresi: " Email Adresi Zorunludur!", ilce: "", il: "", …}
When I disable dataType:"JSON", ı could see console.log(data) of post datas otherwise goesto error:function
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo $data=json_encode(array("status" => TRUE));
}
}
View Ajax:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success:function (data) {
// var obj = $.parseJSON(data);
// $('#data1').html(data);
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
console.log(data.status);
// alert(data.sonuc);
if(data.status){
console.log("false");
}
else{
console.log("true");
console.log(data);
}
},
error:function(data){
console.log("error");
}
});
}
model:
function basvuru_ekle($data)
{
print_r($data);
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
Remove print_r() in insert function and try this:
function save() {
var url;
if (save_method == 'add') {
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
} else {
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
}
},
error: function(data) {
console.log("error");
}
});
}
I checked to find the exact problem.As Alex said problem was because of Print_r() in modal. After I erased it ,now it works fine.
After fixed the problem.
view:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
$('#modal_form').modal('hide');
location.reload();// for reload a page
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) { alert('AJAX page not found.');
}
else {
alert('AJAX Error: ' + textStatus + ': ' + errorThrown); }
}
});
}
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo json_encode(array(
"status" => TRUE,
));
}
}
model:
function basvuru_ekle($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

Add to cart ajax custom product type options

I am trying to add custom product type to product like here wild card
and i succeeded but now i have to add this value to cart with ajax how i suppose to do this with drop-down and shortcode? i just added load_book.js but didn't added any script code because i don't know how to write ajax code for this. thanks.
My code:
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_filter("product_type_options", "woo_bookable_product");
function woo_bookable_product($product_type_options)
{
$product_type_options["Bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => "Bookable",
"description" => "Book Your Product",
"default" => "yes",
);
return $product_type_options;
}
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"] ? 'yes' : 'no';
update_post_meta($product->ID, "_bookable" ,$meta_value);
}
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts','woo_bookable_scripts');
add_action('wp_ajax_woo_bookable_shortcode', 'woo_bookable_shortcode');
add_action('wp_ajax_nopriv_woo_bookable_shortcode', 'woo_bookable_shortcode');
function woo_bookable_shortcode()
{
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable'
));
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
add_shortcode('bookable','woo_bookable_shortcode');
Finally find the solution
PHP:
<?php
/**
* Plugin Name: Bookable
* Description: Add shortcode [bookable] or in php - echo do_shortcode('[bookable]');
* Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter("product_type_options", "woo_bookable_product");
if(!function_exists('woo_bookable_product')):
function woo_bookable_product($product_type_options)
{
$product_type_options["bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => __("Bookable",'woocommerce'),
"description" => __("Check if product is bookable or not",'woocommerce'),
"default" => "no",
);
return $product_type_options;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_add_cart_item_data', 'woo_bookable_custom_field', 10, 2 );
if(!function_exists('woo_bookable_custom_field')):
function woo_bookable_custom_field( $cart_item_data, $product_id )
{
$get_custom_meta = get_post_meta( $product_id , '_bookable', true );
if( $get_custom_meta == 'yes' )
{
$cart_item_data[ '_bookable' ] = $get_custom_meta;
$len = 10;
$word = array_merge(range('a', 'z'), range('A', 'Z'));
$name = shuffle($word);
$name = substr(implode($word), 0, $len);
$cart_item_data['unique_key'] = $name ;
}
return $cart_item_data;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter( 'woocommerce_get_item_data', 'render_woo_bookable_meta_data', 10, 2 );
if(!function_exists('render_woo_bookable_meta_data')):
function render_woo_bookable_meta_data( $cart_data, $cart_item )
{
global $woocommerce;
$custom_items = array();
if( !empty( $cart_data ) )
{
$custom_items = $cart_data;
}
if( isset( $cart_item['_bookable'] ) )
{
$custom_items[] = array(
"name" => __( "Bookable", "woocommerce" ),
"value" => $cart_item['_bookable'] );
$custom_items[] = array(
"name" => __( $cart_item['unique_key'], "woocommerce" ),
"value" => '$10' );
}
return $custom_items;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
if(!function_exists('add_custom_price')):
function add_custom_price( $cart_object )
{
foreach ( $cart_object->get_cart() as $hash => $value )
{
if($value['_bookable'] && $value['data']->is_on_sale())
{
$newprice = $value['data']->get_sale_price()+10;
$value['data']->set_price( $newprice );
}
elseif($value['_bookable'])
{
$not_sell = $value['data']->get_regular_price()+10;
$value['data']->set_price( $not_sell );
}
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_cart_calculate_fees', 'woo_bookable_cart_calculate_totals', 10, 1 );
if(!function_exists('woo_bookable_cart_calculate_totals')):
function woo_bookable_cart_calculate_totals( $cart_object )
{
$get_price = 0;
foreach ( $cart_object->get_cart() as $hash => $value )
{
if(!empty($value['_bookable']))
{
$percent = 10;
$get_price += $value['line_total'];
$fee = ($get_price * $percent) / 100;
}
}
$cart_object->add_fee( __("Bookable Charge($percent%)"),$fee ,false );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
if(!function_exists('woo_save_bookable_data')):
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"];
if(isset($meta_value))
{
$meta_value = 'yes';
update_post_meta( $product->ID, "_bookable" ,$meta_value );
wp_set_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
else
{
delete_post_meta($product->ID, "_bookable");
wp_remove_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('woocommerce_add_order_item_meta','woo_bookable_add_order_meta', 9, 3 );
if(!function_exists('woo_bookable_add_order_meta')):
function woo_bookable_add_order_meta( $item_id, $item_values, $item_key )
{
if( ! empty( $item_values['_bookable'] ) )
wc_update_order_item_meta( $item_id, '_bookable', sanitize_text_field( $item_values['_bookable'] ) );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
add_action( 'admin_notices', 'woo_bookable_active' );
if(!function_exists('woo_bookable_active')):
function woo_bookable_active()
{
$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
?>
<div class="error notice">
<p><?php echo sprintf("Please Activate or <a href='%s'>Install Woocommerce</a> to use Bookable plugin",$err_text); ?></p>
</div>
<?php
//If woocommerce is not installed deactive plugin
if (is_plugin_active('bookable/bookable.php')) {
deactivate_plugins(plugin_basename(__FILE__));
}
unset($_GET['activate']);
}
endif;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('wp_enqueue_scripts','woo_bookable_scripts');
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_shortcode('bookable','woo_bookable_shortcode');
function woo_bookable_shortcode()
{
global $product;
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable',
'meta_value' => 'yes'
) );
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$InArray = array('woo_bookable_product_id','woo_bookable_add_to_cart');
foreach($InArray as $SingleValue)
{
add_action('wp_ajax_'.$SingleValue,$SingleValue);
add_action('wp_ajax_nopriv_'.$SingleValue,$SingleValue);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_product_id()
{
$product_id = $_POST['product_id'];
if($product_id != null && $product_id!=0)
{
$add['id'] = 'success';
$add['msg'] = 'View Cart';
WC()->cart->add_to_cart( $product_id);
}
else
{
$add['id'] = 'fail';
$add['msg'] = 'Please Select Product From DropDown!!';
}
echo json_encode($add);
die();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_add_to_cart()
{
return '<button type="submit" style="margin-left:10px" name="add-to-cart" value="" class="single_add_to_cart_button button alt">Add To Cart</button>
<div class="message"></div>';
die();
}
ajax Script:
jQuery(document).ready(function()
{
jQuery("select.woo_book_pro").change(function(e)
{
var id = jQuery('.woo_book_pro option:selected').val();
var action = 'woo_bookable_add_to_cart';
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"id":id
},
success: function(data)
{
jQuery('.single_add_to_cart_button').attr('value',id);
jQuery('.single_add_to_cart_button').attr("disabled", "disabled");
jQuery('.single_add_to_cart_button').text('WAIT...');
setTimeout(function() {
jQuery('.single_add_to_cart_button').removeAttr("disabled");
jQuery('.single_add_to_cart_button').text('Add To Cart');
}, 3000);
}
});
});
jQuery(".single_add_to_cart_button").click(function(e) {
e.preventDefault();
var product_id = jQuery(this).val();
var action = 'woo_bookable_product_id';
jQuery('.message').empty();
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"product_id":product_id
},
success: function(data)
{
if(data.id == 'success')
{
jQuery('.message').prepend(data.msg);
return false;
}
if(data.id == 'fail')
{
jQuery('.message').prepend(data.msg).css('color','#F33')
return false;
}
}
});
});
});

Wordpress Ajax pagination returning 0 after second time

I am attempting to paginate my posts with an ajax.
I set an attribute "data-page" to the page link and extract it with jQuery to pass it with Ajax.
The first time a click on the link everything works fine but then if I click on a different link the ajax call returns 0.
Here's my code in my functions.php:
wp_register_script('load_post_ajax', get_template_directory_uri() . '/includes/ajax/load_post_ajax.js',array( 'jquery' ), 1.1, true);
$php_array = array( 'admin_ajax' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'load_post_ajax', 'php_array', $php_array );
wp_enqueue_script( 'load_post_ajax' );
/*
* PAGINATION
*/
function hs_pagination($pages = '', $range = 4)
{
$showitems = ($range * 2)+1;
if(isset($_POST['paged'])){
$paged = $_POST['paged'];
}else{
$paged = get_query_var( 'paged', 1 );
}
if(empty($paged)) $paged = 1;
if($pages == '')
{
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages)
{
$pages = 1;
}
}
if(1 != $pages)
{
echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages." </span>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."' data-page=1>« First</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Previous</a>";
for ($i=1; $i <= $pages; $i++)
{
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<a href=\"#\" class=\"current\" data-page=$i>".$i."</a>":"<a href='".get_pagenum_link($i)."' class=\"inactive\" data-page=$i>".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\" data-page=$paged + 1>Next ›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."' data-page=$pages>Last »</a>";
echo "</div>\n";
}
}
/*
* AJAX POSTS LOADER
*/
add_action( 'wp_ajax_load_post_ajax', 'load_post_ajax_init' );
add_action( 'wp_ajax_nopriv_load_post_ajax', 'load_post_ajax_init' );
function load_post_ajax_init() {
$total_posts_per_page = get_option('posts_per_page');
if($_POST['paged']){
$paged = $_POST['paged'];
}else{
$paged = get_query_var( 'paged', 1 );
}
$args = array(
'posts_per_page' => $total_posts_per_page,
'paged' => $paged,
'post_type' => 'post'
);
$posts = query_posts($args);
if($posts){
$count =0;
foreach($posts as $post){
?>
<article class="post">
<?php
if($paged < 2){
if(has_post_thumbnail($post->ID) ){
the_post_thumbnail($post->ID,'big',array('class'=>'img-responsive center-block'));
}else{
echo "no thumb";
}
}else{
echo "not first post";
}
?>
<p class="post_info hs_color"><?php echo $post->post_title . " Posted on: " . $post->post_date . " Author: ". get_the_author_meta( 'display_name',$post->post_author );?></p>
<p><?php echo $post->post_content;?></p>
<div class="post_link clearfix">
<a href="<?php the_permalink($post->ID);?>">
<h6 class="text-uppercase text-center">Read more</h6>
<div class="hs_square hs_square_right hs_bg"></div>
</a>
</div>
</article>
<?php
$count++;
}
}else {
echo "no posts found";
}
//PAGINATION
hs_pagination();
//PAGINATION
}
/*
*AJAx CALL
*/
jQuery( document ).ready(function() {
$('#post-section .container .pagination a').on('click',function(e){
/** Prevent Default Behaviour */
e.preventDefault();
var page = $(this).attr('data-page');
/** Ajax Call */
$.ajax({
cache: false,
timeout: 8000,
url: php_array.admin_ajax,
type: "POST",
data: ({
action:'load_post_ajax',
paged:page,
}),
beforeSend: function() {
},
success: function( data,response ){
$( '#post-section .container' ).addClass('animated FadeIn');
$( '#post-section .container' ).html( data);
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( 'The following error occured: ' + textStatus, errorThrown );
},
});
});
});

Resources