I compiled my data into JSON via php with 2 parameters response and status. Response has the data which PHP gets when AJAX is processed and status is the error code or success command.
Now, when I pass the data to jQuery, it comes up with weird back and forward slashes, although are don't appear if I console.log(data.response) on AJAX. Please help ..
IMAGE OF OUTPUT
THE JS:
jQuery(document).ready(function($) {
$('.tax-filter').click( function(event) {
// Prevent defualt action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = $(this).attr('title');
$('.tagged-posts').fadeOut();
data = {
action: 'filter_posts',
afp_nonce: afp_vars.afp_nonce,
taxonomy: selecetd_taxonomy,
};
$.ajax({
type: 'post',
dataType: 'json',
url: afp_vars.afp_ajax_url,
data: data,
success: function( data, textStatus, XMLHttpRequest ) {
$('.tagged-posts').html( data.response );
$('.tagged-posts').fadeIn();
/*console.log( data );
console.log( XMLHttpRequest );*/
},
error: function( MLHttpRequest, textStatus, errorThrown ) {
/*console.log( MLHttpRequest );
console.log( textStatus );
console.log( errorThrown );*/
$('.tagged-posts').html( 'No posts found' );
$('.tagged-posts').fadeIn();
}
})
});
});
THE PHP (WP)
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
wp_reset_postdata();
// WP Query
$args = array(
'post_type' => 'std9_photographs',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'std9_photograph_cat',
'field' => 'slug',
'terms' => $taxonomy,
),
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
$result = '';
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$result['response'][] = '<h2>'. get_the_title().' </h2>';
$result['status'] = 'success';
endwhile; else:
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
$result = json_encode($result);
echo $result;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
JSON will add slashes when needed (so don't worry about that). The problem is that jQuery has problem to parse that data. You are probably facing a problem encoding your response.
Edit: In order to avoid your backslashes try encoding with the following command json_encode($str, JSON_UNESCAPED_SLASHES);
The reason that you are having this forward and back slashes is because you are adding in your response html code with </h2> </a> etc.
First of all make sure your header is: header('Content-Type: application/json');
Secondly, do a JSON.parse() in your javascript to parse response into json object.
Related
I am trying to improve the speed of my infinite scroll code. Here is my ajax requet handling script
function ga_infinite_scroll() {//trigger this on infinite scroll
add_filter( 'woocommerce_get_price_html', 'ga_show_price' );//filter to fix price range
if(empty($_POST['search_term'] )){
$params = json_decode( stripslashes( $_POST['query'] ), true );
$params['post_status'] = 'publish';
$params['posts_per_page'] = get_option('posts_per_page');
$params['post_type'] = 'product';
$params['paged'] = $_POST['page'] + 1; // we need next page to be loaded
}
else{//search logic here
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
$params = $search_query;
}
ob_start();
query_posts( $params);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
}
add_action( 'wp_ajax_ga_infinite_scroll', 'ga_infinite_scroll' );
add_action( 'wp_ajax_nopriv_ga_infinite_scroll', 'ga_infinite_scroll' );
Here is my javascript:-
jQuery(document).ready( function($) {
var url = window.location.origin + '/wp-admin/admin-ajax.php',
canBeLoaded=true,
bottomOffset = 2000; // the distance (in px) from the page bottom when you want to load more posts
$(window).scroll(function(){
var data = {
'action': 'ga_infinite_scroll',
'query': my_ajax_object.posts,
'page' : my_ajax_object.current_page,
//'search_results' : my_ajax_object.ga_search_results,
'search_count' : my_ajax_object.ga_search_count,
'search_posts': my_ajax_object.ga_search_posts,
'search_term' : my_ajax_object.ga_search_term,
'user_currency': my_ajax_object.user_currency,
'reg_price_slug': my_ajax_object.reg_price_field_slug
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({//limit the ajax calls
url : url,
data:data,
type:'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
//console.log(data.search_term);
$('#ajax-loader').show();
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#multiple-products .columns-3 .products ').find('li:last-of-type').after( data ); // where to insert posts
//console.log(url);
canBeLoaded = true; // the ajax is completed, now we can run it again
my_ajax_object.current_page++;
$('#ajax-loader').hide();
}
else{
$('#ajax-loader').html('End of products...').delay(1000).fadeOut();
return;
}
}
});
}
});
//setting if it's a search
});
I'm wondering if it's a good idea to use query_posts and I have this filter that costly in terms of speed but if I don't use it, I end up seeing a price range like this $15-$25 like that.Any idea about how to handle this situation and to see the code of ga_show_price and my enqueued script, I've added it here Improving the speed of a custom infinite scroll and also any suggestions on improving my javascript?Thanks
You can get related products using the following:
$array = wc_get_related_products( $product_id, $limit, $exclude_ids );
I have searched all over here and the web but cant seem to get this to work - hopefully you all can help.
I am trying to setup product filters for WooCommerce on the category page (like filter products depending on color etc)
I have the ajax working but I have a shortcode that I want to display for each product and this doesnt work - any ideas how to get it to show?
Code below:
PHP
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', plugins_url() . '/plugin-name/js/product-filter-ajax.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
JS
jQuery(document).ready(function($) {
$(".loading").hide();
var taxonomy = [];
var terms = [];
$('.filter-option input').click( function(event) {
var taxonomy_idx = $.inArray($(this).closest(".filter-title-wrapper").attr('data-attribute'), taxonomy);
if (taxonomy_idx == -1) {
taxonomy.push($(this).closest(".filter-title-wrapper").attr('data-attribute'));
} else {
taxonomy.splice(taxonomy_idx, 1);
}
var terms_idx = $.inArray($(this).val(), terms);
if (terms_idx == -1) {
terms.push($(this).val());
} else {
terms.splice(terms_idx, 1);
}
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = taxonomy.toString();;
var selected_term = terms.toString();
var selected_term_speach = '\'' + selected_term.split(',').join('\',\'') + '\'';
console.log(selecetd_taxonomy);
console.log(selected_term_speach);
// After user click on tag, fade out list of posts
$('.products').fadeOut();
$(".loading").fadeIn();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
term: selected_term_speach,
};
$.post( afp_vars.afp_ajax_url, data, function(response) {
$(".loading").fadeOut();
if( response ) {
// Display posts on page
$('.products').html( response );
// Restore div visibility
$('.products').fadeIn();
};
});
});
});
PHP TO GET POSTS
// Script for getting posts
function ajax_filter_get_posts( $taxonomy, $term ) {
ob_start();
global $woocommerce, $product;
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
$term = $_POST['term'];
$term = str_replace("\\", '', $term);
// WP Query
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
);
if ($term == "''") {
}
else {
$args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => array($term),
'field' => 'slug',
'operator' => 'IN'
),
)
);
}
?>
<h1> <?php echo $term ?> </h1>
<?php
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<li <?php wc_product_class(); ?>>
<?php echo do_shortcode('[product_shortcode]'); ?>
</li>
<?php
?>
<?php endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
return ob_get_clean();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Excuse the messyness of the code, just trying to get it to work before I can start to neaten it up. Any advice on how to approach this in a better way please let me know.
Thanks and appreciate the help!
UPDATE-----
Tried to add the shortcode callback, but this doesnt work or I have the wrong code
add_action( 'init', function() {
ps_register_shortcode_ajax( 'ajax_filter_get_posts', 'ajax_filter_get_posts' );
} );
function ps_register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
WordPress Ajax calls don't have the access to whole WordPress environment and that's why your shortcode not working. Instead of calling the shortcode directly, call its callback. Refer https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request for more details.
So i'm trying to make a follow button in wp, and for some reason the ajax button isn't working right.
Here are the steps of what's supposed to happen
user clicks #followbtn
Ajax goes to $_POST action that = follow
php runs wp_set_object_terms( $user_id, $author_id, 'follow', true );
when that's done the function echo's "ok"
if the data = ok reload the page
For some reason the php isn't executing and the page isn't being reloaded.
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta( 'nickname' ); // get authors name
$termId = get_term_by( 'slug', $author_id, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$author_follow_count = count( $followers );
if ( is_user_logged_in() ) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
echo "ok";
}
}
}
exit;
}
Front end button
function getAuthorFollowLink( $author_id ) {
$author = get_the_author_meta( 'nickname' );
$user_ID = get_current_user_id();
$termId = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$count = count( $followers );
$output = 'Folllow '.$count.'';
return $output;
}
js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
Try disabling this code
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
If You know the implications. You might want to learn more https://codex.wordpress.org/Function_Reference/wp_verify_nonce
In 3 different AJAX scripts that I have written the error message is displayed even though the ajax is processes the PHP file updated and all the success statements are executed. Since I only discovered ajax a few days ago. There must be something wrong with my scripts. Perhaps someone could see where I have gone wrong.
AJAX:
function bookingdetails() {
var actdate = $('#actdate').val();
var airport = $('#FLTairport').val();
var number = $('#FLTnumber').val();
var time = $('#FLTtime').val();
var dataString = 'actdate=' + actdate + '&airport=' + airport + '&number=' + number + '&time=' + time;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?update',
data: dataString,
beforeSend: function() {
$('#airloader').html('<img id="BKloader" src="http://www.divethegap.com/update/z-images/structure/icons/blockloader.gif" alt="" width="30" height="30"/>');
},
error: function() {
$('#airloader').html('arse up');
},
dataType:'json',
success: function(data) {
$('#actdate').val(data.date);
$('#FLTnumber').val(data.FLTnumber);
$('#airloader').html('marvellous');
$('#FLTairport').val(data.FLTairport);
$('#FLTdate').val(data.FLTdate);
$('#FLTtime').val(data.FLTtime);
$('#datediv').load('<?php echo $thisposturl;?> #datediv');
}
});
}
PHP : (dont worry about the insert post bits)
<?php
function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
if ( is_user_logged_in() ) {
$my_post = array(
'ID' => get_the_ID(),
'post_date' => $_POST['actdate'],
);
$the_post_id = wp_update_post( $my_post );
__update_post_meta( $the_post_id, 'FLTairport', $_POST['airport'] );
__update_post_meta( $the_post_id, 'FLTnumber', $_POST['number'] );
__update_post_meta( $the_post_id, 'FLTtime', $_POST['time'] );
}
$FLTdate = get_the_time('d/m/Y');
$actdate = get_the_time('Y-m-d');
$FLTairport = $_POST['airport'];
$FLTnumber = $_POST['number'];
$FLTtime = $_POST['time'];
echo json_encode( array('FLTdate'=>$FLTdate, 'actdate'=>$actdate, 'FLTairport'=>$FLTairport, 'FLTnumber'=>$FLTnumber, 'FLTtime'=>$FLTtime));
?>
Result all values are updated but it still displays 'arse up' in the #airloader. This is one example I can provide it with 3 out of 4 of the ajax scripts that I have written.
Any ideas?
Marvellous
Have you checked the second parameter to your error function?
See: http://api.jquery.com/jQuery.ajax/
error(jqXHR, textStatus, errorThrown)
..., a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". ...
I am using the following ajax to update information on a page and then resubmit the page into the database. The script is failing each time stopping at the Error parameter. Can anyone see where I have gone wrong.
AJAX -
function bookingdetails() {
var date = <?php the_time('Y-m-d');?>;
var airport = $('#FLTairport').val();
var number = $('#FLTnumber').val();
var time = $('#FLTtime').val();
var dataString = 'date=' + date + '&airport=' + airport + '&number=' + number + '&time=' + time;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?update',
data: dataString,
beforeSend: function() {
$('#airloader').html('<img id="BKloader" src="http://www.divethegap.com/update/z-images/structure/icons/blockloader.gif" alt="" width="40" height="30"/>');
},
error: function() {
$('#airloader').html('Failed to update booking, try again');
},
dataType:'json',
success: function(data) {
$('#date').val(data.date);
$('#FLTnumber').val(data.FLTnumber);
$('#airloader').val(data.FLTnumber);
$('#FLTairport').val(data.FLTairport);
$('#FLTdate').val(data.FLTdate);
$('#FLTtime').val(data.FLTtime);
}
});
}
PHP -
<?php
function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
if ( is_user_logged_in() ) {
$my_post = array(
'ID' => get_the_ID(),
'post_date' => $_POST['date'],
);
$the_post_id = wp_update_post( $my_post );
__update_post_meta( $the_post_id, 'FLTairport', $_POST['airport'] );
__update_post_meta( $the_post_id, 'FLTnumber', $_POST['number'] );
__update_post_meta( $the_post_id, 'FLTtime', $_POST['time'] );
}
$FLTdate = get_the_time('d/m/Y');
$date = get_the_time('Y-m-d');
$FLTairport = $_POST['airport'];
$FLTnumber = $_POST['number'];
$FLTtime = $_POST['time'];
echo json_encode( array('FLTdate'=>$FLTdate, 'date'=>$date, 'FLTairport'=>$FLTairport, 'FLTnumber'=>$FLTnumber, 'FLTtime'=>$FLTtime));
?>
Any ideas?
Marvellous
The jQuery Documentation shows 3 arguments that can be used in your error callback, which could be very useful in debugging your error.
From the docs
so with that in mind, try changing your error callback like so...
error: function(xhr,ts,et) {
$('#airloader').html('Failed to update booking.');
$('#airloader').append('Error Text - '+ts);
},
and you should see the specific error, which should put you down the right path to fix it.
Are you able to see what your php script is sending? I would recommend using firebug in firefox to see exactly what is coming back to be consumed by your javascript. I don't see where it is outputting a success parameter for your json.