Reload wordpress php part with ajax - javascript

Im using wordpress theme that has different parts like for example footer.php or header.php. What I want to do is reload one part of the whole page using jquery so that the whole page does not refresh. Below is my code with the php part that I want to reload and the jquery Im using.
Jquery code inside a php code block
<script type="text/javascript">
jQuery(document).ready(function(){
var thedata = '.json_encode($this->query_args).';
jQuery( ".facetwp-page" ).click(function() {
jQuery.ajax({
type: "post",
url: "'.admin_url("admin-ajax.php").'",
data: { "action" : "query_for_map", "mydata" : thedata },
success: function(response, data){
console.log(response);
console.log(data);
jQuery("#map-head").load("'.get_template_directory_uri().'/banners/map_based_banner.php");
google.maps.event.trigger(map, "resize");
}
});
});
});
</script>
php template part to be reloaded
<?php
session_start();
include('/home/javy1103/public_html/wp-blog-header.php');
global $paged;
$properties_for_map = array(
'post_type' => 'property',
'posts_per_page' => 12,
'paged' => $paged
);
if( is_page_template('template-search.php') || is_page_template('template-search-sidebar.php') ){
/* Apply Search Filter */
$properties_for_map = apply_filters( 'real_homes_search_parameters', $properties_for_map );
}elseif(is_page_template('template-home.php')){
/* Apply Homepage Properties Filter */
$properties_for_map = apply_filters( 'real_homes_homepage_properties', $properties_for_map );
}elseif(is_tax()){
global $wp_query;
/* Taxonomy Query */
$properties_for_map['tax_query'] = array(
array(
'taxonomy' => $wp_query->query_vars['taxonomy'],
'field' => 'slug',
'terms' => $wp_query->query_vars['term']
)
);
}
function query_for_map() {
return json_decode($_POST['mydata']);
}
add_action('wp_ajax_query_for_map', 'query_for_map');
add_action('wp_ajax_nopriv_query_for_map', 'query_for_map');
$mapdata = $_SESSION['queryMap'];
$properties_for_map_query = new WP_Query( $mapdata );
$properties_data = array();
if ( $properties_for_map_query->have_posts() ) :
while ( $properties_for_map_query->have_posts() ) :
$properties_for_map_query->the_post();
$current_prop_array = array();
/* Property Title */
$current_prop_array['title'] = get_the_title();
/* Property Price */
$current_prop_array['price'] = get_property_price();
/* Property Location */
$property_location = get_post_meta($post->ID,'REAL_HOMES_property_location',true);
if(!empty($property_location)){
$lat_lng = explode(',',$property_location);
$current_prop_array['lat'] = $lat_lng[0];
$current_prop_array['lng'] = $lat_lng[1];
}
/* Property Thumbnail */
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_attributes = wp_get_attachment_image_src( $image_id, 'property-thumb-image' );
if(!empty($image_attributes[0])){
$current_prop_array['thumb'] = $image_attributes[0];
}
}
/* Property Title */
$current_prop_array['url'] = get_permalink();
/* Property Map Icon Based on Property Type */
$property_type_slug = 'single-family-home'; // Default Icon Slug
$type_terms = get_the_terms( $post->ID,"property-type" );
if(!empty($type_terms)){
foreach($type_terms as $typ_trm){
$property_type_slug = $typ_trm->slug;
break;
}
}
if(file_exists(get_template_directory().'/images/map/'.$property_type_slug.'-map-icon.png')){
$current_prop_array['icon'] = get_template_directory_uri().'/images/map/'.$property_type_slug.'-map-icon.png';
}else{
$current_prop_array['icon'] = get_template_directory_uri().'/images/map/single-family-home-map-icon.png';
}
$properties_data[] = $current_prop_array;
endwhile;
wp_reset_query();
?>

You can generate all server side(PHP) work without refreshing page by Ajax, Then you can use it in HTML, you can't replace PHP of your page.
ex: If you want some data from database then you can send an ajax request to PHP file then fetch the data and get the result, then show it in HTML.

Related

WordPress Ajax post load

I've been trying (and failing annoyingly) to get an Ajax post loader to work.
This is the jQuery i'm using (its from this previous StackOverflow post: "Load More Posts" with Ajax in wordpress ), but its just not working.. I'm just trying to get an isotope list to ajax load more but everything i'm trying is failing.
jQuery(document).ready(function($){
$('.pagination a').click(function(e) {
e.preventDefault();
$('.filtered-posts').append("<div class=\"loader\"> </div>");
var link = jQuery(this).attr('href');
var $content = '.filtered-posts';
var $nav_wrap = '.pagination';
var $anchor = '.pagination a';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$.get(''+link+' .item', function(data){
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
$('.filtered-posts .loader').remove();
$next_href = $($anchor, data).attr('href'); // Get the new href
$($nav_wrap).before($new_content); // Append the new content
$('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('.pagination a').attr('href', $next_href); // Change the next URL
$('.pagination:last').remove(); // Remove the original navigation
});
});});
This is what I'm using for my js but its just not loading anything when I click on the standard previous_posts_link/next_posts_link.
I've put a div container around them to force the .pagination above.. It briefly worked but was only calling the same 9 posts once and then didn't work.
Any help would be great. Or if someone has a different Ajax Pagination guide that they know works ..
Thanks in advance :)
/* We will edit our javascript snippet with a variable to keep track of the current page, and we add the $ajax call to our ajax function that we will write in the next chapter. */
let currentPage = 1;
jQuery('#load-more').on('click', function() {
currentPage++; // Do currentPage + 1, because we want to load the next page
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
dataType: 'html',
data: {
action: 'weichie_load_more',
paged: currentPage,
},
success: function (res) {
jQuery('.publication-list').append(res);
}
});
});
/* The WordPress query to load posts from a (custom) post type */
<?php
$publications = new WP_Query([
'post_type' => 'publications',
'posts_per_page' => 6,
'orderby' => 'date',
'order' => 'DESC',
'paged' => 1,
]);
?>
<?php if($publications->have_posts()): ?>
<ul class="publication-list">
<?php
while ($publications->have_posts()): $publications->the_post();
get_template_part('parts/card', 'publication');
endwhile;
?>
</ul>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<div class="btn__wrapper">
Load more
</div>
functions.php:
function weichie_load_more() {
$ajaxposts = new WP_Query([
'post_type' => 'publications',
'posts_per_page' => 6,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $_POST['paged'],
]);
$response = '';
if($ajaxposts->have_posts()) {
while($ajaxposts->have_posts()) : $ajaxposts->the_post();
$response .= get_template_part('parts/card', 'publication');
endwhile;
} else {
$response = '';
}
echo $response;
exit;
}
add_action('wp_ajax_weichie_load_more', 'weichie_load_more');
add_action('wp_ajax_nopriv_weichie_load_more', 'weichie_load_more');

AJAX load more function multiplies the old data?

I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own

WooCommerce Ajax Cart Update Stopped Working

I found a function to automatically update the cart when the quantity of an item is changed, and it was working until WooCommerce's 3.2.0 updated (latest update 3.2.1). I'm pretty sure something changed within this code:
add_action('woocommerce_cart_updated', 'wac_update');
function wac_update() {
// is_wac_ajax: flag defined on wooajaxcart.js
if ( !empty($_POST['is_wac_ajax'])) {
$resp = array();
$resp['update_label'] = __( 'Update Cart', 'woocommerce' );
$resp['price'] = 0;
// render the cart totals (cart-totals.php)
ob_start();
do_action( 'woocommerce_after_cart_table' );
do_action( 'woocommerce_cart_collaterals' );
do_action( 'woocommerce_after_cart' );
$resp['html'] = ob_get_clean();
// calculate the item price
if ( !empty($_POST['cart_item_key']) ) {
$items = WC()->cart->get_cart();
$cart_item_key = $_POST['cart_item_key'];
if ( array_key_exists($cart_item_key, $items)) {
$cart_item = $items[$cart_item_key];
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$price = apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
$resp['price'] = $price;
}
}
echo json_encode($resp);
exit;
}
}
My Javascript still working but here it is for a reference:
function refreshCart() {
jQuery('.cart-builder .qty').on('change', function(){
var form = jQuery(this).closest('form');
// emulates button Update cart click
jQuery("<input type='hidden' name='update_cart' id='update_cart' value='1'>").appendTo(form);
// plugin flag
jQuery("<input type='hidden' name='is_wac_ajax' id='is_wac_ajax' value='1'>").appendTo(form);
var el_qty = jQuery(this);
var matches = jQuery(this).attr('name').match(/cart\[(\w+)\]/);
var cart_item_key = matches[1];
form.append( jQuery("<input type='hidden' name='cart_item_key' id='cart_item_key'>").val(cart_item_key) );
// get the form data before disable button...
var formData = form.serialize();
jQuery("input[name='update_cart']").val('Updating...').prop('disabled', true);
jQuery.post( form.attr('action'), formData, function(resp) {
// ajax response
jQuery('.cart-collaterals').html(resp.html);
el_qty.closest('.cart_item').find('.product-subtotal').html(resp.price);
console.log(resp.test);
jQuery('#update_cart').remove();
jQuery('#is_wac_ajax').remove();
jQuery('#cart_item_key').remove();
jQuery("input[name='update_cart']").val(resp.update_label).prop('disabled', false);
},
'json'
);
});
}
I've been looking through the change log, https://github.com/woocommerce/woocommerce/blob/master/CHANGELOG.txt, but I can't find what would be conflicting now. Like I said, it was working perfectly before this updated.
Ok here is a simpler solution, I am just appending a script to the bottom of the cart page but you could also enqueue it with wp_enqueue_script function which is the best way. All it does it simulates the pressing of the update cart button.
function cart_update_qty_script() {
if (is_cart()) :
?>
<script type="text/javascript">
(function($){
$(function(){
$('div.woocommerce').on( 'change', '.qty', function(){
$("[name='update_cart']").trigger('click');
});
});
})(jQuery);
</script>
<?php
endif;
}
add_action( 'wp_footer', 'cart_update_qty_script' );

Why ajax request isn't sending all the data?

I'm working in a ecommerce with wordpresss and woocommerce, im adding to the shop page and category pages buttons that display the sizes for each product. with this code inside the theme function:
function woocommerce_variable_add_to_carts() {
global $product, $post;
$variations = $product->get_available_variations();
$product_sku = $product->get_sku();
$out = '<ul class="iconic-was-swatches iconic-was-swatches--loop iconic-was-swatches--text-swatch iconic-was-swatches--square">';
foreach ($variations as $key => $value) {
if (!empty($value['attributes'])) {
foreach ($value['attributes'] as $attr_key => $attr_value) {
$out .= '<li><a id="'.esc_attr($post->ID).'" data-quantity="1" data-product_id="'.esc_attr($post->ID).'" data-product_sku="'.$product_sku.'" class="iconic-was-swatch iconic-was-swatch--follow iconic-was-swatch--text-swatch add_to_cart_button">';
$out .= $attr_value . '</a></li>';
}
}
}
$out .= '</ul>';
echo $out;
}
add_action('woocommerce_before_shop_loop_item_title', 'woocommerce_variable_add_to_carts');
The idea is that when the users click in one of those sizes buttons the product is added to the cart directly in that page (shop page, category page). I made a custom endpoint to solve that from the answer provided here. I call the ajax function in the js file that Contains this:
$('.add_to_cart_button').on('click',function(){
jQuery.ajax({
url: WC_VARIATION_ADD_TO_CART.ajax_url,
type: "POST",
data: {
action : "customAdd_to_cart",
product_id : "697",
variation_id : "707",
quantity : 1,
variation : {
size : "s",
color: "pink"
}
},
success: function(){
alert('Ajax Success ');
}
});
});
(i'm using a specific product_id and variation_id for testing) then i add the callback function in the themes function page to add the products to the cart :
function customAddToCart() {
ob_start();
try {
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $data['product_id'] ) );
$quantity = empty( $data['quantity'] ) ? 1 : wc_stock_amount( $data['quantity'] );
$variation_id = isset( $data['variation_id'] ) ? absint( $data['variation_id'] ) : '';
$variations = $variation_id ? (array) get_variation_data_from_variation_id( $variation_id ) : null;
$product_status = get_post_status( $product_id );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );
if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
$res = getCartFragments();
} else {
$res = array(
'error' => true
);
}
return $res;
} catch (Exception $e) {
return new WP_Error('add_to_cart_error', $e->getMessage(), array('status' => 500));
}
}
add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'customAddToCart' );
all this seems to work fine because doesn't give any error in console but the problems is that the variation Size in not added with the product that is selected just add the product. I dont know why this is happening, i even add an alert in the ajax success function
alert('Ajax Success ');
and that alert is displayed but the data it seems is not been sending like it should.
i want to know what i'm missing in any of this codes or it could be the js file and his location or i need to send another value in the a> builded in the first function above. i have try a lot things but the behavior still the same.
A quick scan over your code and I've noticed that the action you are calling with ajax is not correct. It should be woocommerce_add_variation_to_cart not customAdd_to_cart. Also it is common practice to use wp_send_json (or the more specific wp_send_json_success and wp_send_json_error functions) at the end of your ajax callback function so that you get a readable and sensible response in jQuery. Check out the following link if you have not used it before:
https://codex.wordpress.org/Function_Reference/wp_send_json
Hope this helps.

Cannot populate select fields with AJAX in Wordpress - UPDATE

UPDATE: My ajax function for handling the response is correct, but I have a hard time to iterate through the response object and populate the select field. I've tried and with for loop instead of each() and is working better but the select field was populated with "undefined". Any ideas?
Below is my Jquery code
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
var nomos_name = $('#nomoi-select option:selected').attr('id');
var jsonMimeType = "application/json;charset=UTF-8";
type = 'POST';
data = { 'parent_id': nomos_name, action : 'get_child_categories' };
dataType = 'json';
contentType = "application/json; charset=utf-8";
processData = false;
$.post( ajaxurl, data, function(response) {
if( response ){
console.log(response);
var content = '';
var data = JSON.stringify(response);
$(data).each(function(key, value) {
content += '<option>' + value + '</option>';
});
$(content).appendTo("#town-select");
}
});
}).change();
});
My ajax function:
function get_child_categories() {
if (isset($_POST['parent_id'])) {
$parent_id = ($_POST['parent_id']);
$result = array();
$args = array(
'post_type' => 'seller',
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'hierarchical' => 1,
'child_of' => $parent_id
);
$categories = get_categories( $args );
foreach ( $categories as $cat ) {
$result = array(
'town_id' => $cat->cat_ID,
'town_name' => $cat->cat_name
);
echo json_encode($result);
}
}
die();
}
add_action('wp_ajax_get_child_categories', 'get_child_categories');
add_action('wp_ajax_nopriv_get_child_categories', 'get_child_categories');
The OnChange is working fine and I get the following output from log:
{"town_id":"41","town_name":"\u0391\u0393\u0393\u0395\u039b\u039f\u039a\u0391\u03a3\u03a4\u03a1\u039f"}{"town_id":"42","town_name":"\u0391\u0393\u03a1\u0399\u039d\u0399\u039f"}{"town_id":"40","town_name":"\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f"}{"town_id":"84","town_name":"\u0391\u039b\u03a5\u0396\u0399\u0391"}{"town_id":"85","town_name":"\u0391\u039c\u03a6\u0399\u039b\u039f\u03a7\u0399\u0391"}{"town_id":"86","town_name":"\u0391\u039d\u0391\u039a\u03a4\u039f\u03a1\u0399\u039f"}{"town_id":"87","town_name":"\u0391\u039d\u03a4\u0399\u03a1\u03a1\u0399\u039f"}{"town_id":"88","town_name":"\u0391\u03a0\u039f\u0394\u039f\u03a4\u0399\u0391"}{"town_id":"89","town_name":"\u0391\u03a1\u0391\u039a\u03a5\u039d\u0398\u039f\u03a3"}{"town_id":"90","town_name":"\u0391\u03a3\u03a4\u0391\u039a\u039f\u03a3"}{"town_id":"91","town_name":"\u0398\u0395\u03a1\u039c\u039f"}{"town_id":"92","town_name":"\u0398\u0395\u03a3\u03a4\u0399\u0395\u03a9\u039d"}{"town_id":"93","town_name":"\u0399\u0395\u03a1\u0391\u03a3 \u03a0\u039f\u039b\u0397\u03a3 \u039c\u0395\u03a3\u039f\u039b\u039f\u0393\u0393\u0399\u039f\u03a5"}{"town_id":"94","town_name":"\u0399\u039d\u0391\u03a7\u039f\u03a5"}{"town_id":"95","town_name":"\u039c\u0391\u039a\u03a1\u03a5\u039d\u0395\u0399\u0391\u03a3"}{"town_id":"96","town_name":"\u039c\u0395\u0394\u0395\u03a9\u039d\u039f\u03a3"}{"town_id":"97","town_name":"\u039c\u0395\u039d\u0399\u0394\u0399\u039f\u03a5"}{"town_id":"98","town_name":"\u039d\u0391\u03a5\u03a0\u0391\u039a\u03a4\u039f\u03a5"}{"town_id":"99","town_name":"\u039d\u0395\u0391\u03a0\u039f\u039b\u0397\u03a3"}{"town_id":"100","town_name":"\u039f\u0399\u039d\u0399\u0391\u0394\u03a9\u039d"}{"town_id":"101","town_name":"\u03a0\u0391\u039b\u0391\u0399\u03a1\u039f\u03a5"}{"town_id":"102","town_name":"\u03a0\u0391\u039d\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f\u03a5"}{"town_id":"103","town_name":"\u03a0\u0391\u03a1\u0391\u0392\u039f\u039b\u0391\u03a3"}{"town_id":"104","town_name":"\u03a0\u0391\u03a1\u0391\u039a\u0391\u039c\u03a0\u03a5\u039b\u0399\u03a9\u039d"}{"town_id":"105","town_name":"\u03a0\u039b\u0391\u03a4\u0391\u039d\u039f\u03a5"}{"town_id":"106","town_name":"\u03a0\u03a5\u039b\u039b\u0397\u039d\u0397\u03a3"}{"town_id":"107","town_name":"\u03a3\u03a4\u03a1\u0391\u03a4\u039f\u03a5"}{"town_id":"108","town_name":"\u03a6\u03a5\u03a4\u0395\u0399\u03a9\u039d"}{"town_id":"109","town_name":"\u03a7\u0391\u039b\u039a\u0395\u0399\u0391\u03a3"}
Taking the hint from Tom Kriek:
You could always build all of the tags inside the php
script,and then return that to the function. This saves you iterating
it on the ajax side. All you have to do then is stick the html in the
right spot. Namely in the select tag.
I've used $(#town-select).html(response); in the JQuery response and worked perfectly. Thanx everybody!

Categories

Resources