WooCommerce Ajax Add to Cart facebook pixel event not working - ajax

Add to Cart Facebook pixel event is not being triggered when adding product to cart with Ajax.
Here is my first output in head.
<!-- WooCommerce Facebook Integration Begin -->
<script <?php echo self::get_script_attributes(); ?>>
<?php echo $this->get_pixel_init_code(); ?>
fbq( 'track', 'PageView', <?php echo json_encode( self::build_params( [], 'PageView' ), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT ) ?> );
document.addEventListener('DOMContentLoaded', function() {
jQuery && jQuery(function($){
$('body').on( 'added_to_cart', function()
{
// Testing output on browser JS console
console.log('added_to_cart');
$( 'body' ).append( '<div class=\"wc-facebook-pixel-event-placeholder\"></div>' );
});
});
}, false);
</script>
When adding product to cart, "added_to_cart" is printed in console. So the add to cart Ajax is working.
Here is the function that is not being trigger with Ajax.
// AddToCart while AJAX is enabled
add_action( 'woocommerce_ajax_added_to_cart', [ $this, 'add_filter_for_add_to_cart_fragments' ] );
// Setups a filter to add an add to cart fragment whenever a product is added to the cart through Ajax.
public function add_filter_for_add_to_cart_fragments() {
if ( 'no' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
add_filter( 'woocommerce_add_to_cart_fragments', [ $this, 'add_add_to_cart_event_fragment' ] );
}
}
// Adds an add to cart fragment to trigger an AddToCart event.
public function add_add_to_cart_event_fragment( $fragments ) {
if ( self::$isEnabled ) {
$script = $this->pixel->get_event_script( 'AddToCart', [
'content_ids' => $this->get_cart_content_ids(),
'content_type' => 'product',
'contents' => $this->get_cart_contents(),
'value' => $this->get_cart_total(),
'currency' => get_woocommerce_currency(),
] );
$fragments['div.wc-facebook-pixel-event-placeholder'] = '<div class="wc-facebook-pixel-event-placeholder">' . $script . '</div>';
}
return $fragments;
}
I'm using latest Wordpress & WooCommerce with Facebook for WooCommerce plugin.

Related

How to set an ajax url in wordpress? I want to call it with datatables.net in server side processing mode

I want to set up an ajax url to use it with Datatables in wordpress. But I don't know how I would set up the corresponding url in wordpress. I guess its a rather easy task but don't know how to do it.
I found example code how to set up datatables server side processing in wordpress but I am struggling to put the following code in real life (how to create the corresponding FrontendConfig.ajaxurl in Wordpress? Or would it be better to create a wordpress json endpoint?)
jQuery
jQuery('#student_table').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
"url": FrontendConfig.ajaxurl+'?action=getStudentsFromExamIdAjax&exam_nounce=exam_nounce_data&exam_id=1',
type: "post",
}
});
Wordpress php
add_action('wp_ajax_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' );
add_action('wp_ajax_nopriv_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' );
function getStudentsFromExamIdAjax(){
if(empty($_GET['action']) || empty($_GET['exam_id'])){
wp_send_json_error( new \WP_Error( 'Bad Request' ) );
}
if(isset($_GET['exam_id']) && $_SERVER['REQUEST_METHOD'] === 'POST' && wp_verify_nonce( $_GET['exam_nounce'], 'exam_nounce_data' )):
$exam_id = (isset($_GET['exam_id'])) ? absint($_GET['exam_id']) : '';
/*# You can create a function to get the data here */
$students = getStudentsFromExamId($exam_id);
$tdata = [];
foreach ($students as $key => $value):
$tdata[$key][] = $value->roll_no;
$tdata[$key][] = $value->name;
$tdata[$key][] = $value->phone;
$tdata[$key][] = 'action here';
endforeach;
$total_records = count($tdata);
$json_data = array(
/* $_REQUEST['draw'] comes from the datatable, you can print to ensure that */
"draw" => intval( $_REQUEST['draw'] ),
"recordsTotal" => intval( $total_records ),
"recordsFiltered" => intval( $total_records ),
"data" => $tdata
);
echo json_encode($json_data);
endif;
wp_die();
}
You just need to set the following enqueue_style_and_scripts into your function.php file. You need to set wp_localize_script, check this link https://developer.wordpress.org/reference/functions/wp_localize_script/. Don't forget to change the code as per your coding requirement.
/*# Enqueue styles & scripts */
if( !function_exists('enqueue_style_and_scripts') ):
function enqueue_style_and_scripts(){
$version = wp_get_theme()->get('Version');
wp_enqueue_script(
'general_js',
get_stylesheet_directory_uri() . '/assets/js/general.js',
array('jquery'),
$version,
true
);
$frontendconfig = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'is_user_logged_in' => is_user_logged_in(),
);
wp_localize_script( 'general_js', 'FrontendConfig', $frontendconfig );
}
add_action('wp_enqueue_scripts', 'enqueue_style_and_scripts');
endif;

ReferenceError: ajax_object is not defined when loading Wordpress post via Ajax

I've been trying to implement the recommendation by #SagiveSEO in this thread:
Proper way to load a single post via Ajax?
The idea: click a button and load a post via AJAX. The idea being that you'll have a tree of buttons to allow people to navigate quickly to useful content.
Unfortunately, it fails.
In the console I get the message "ReferenceError: ajax_object is not defined" which refers to the line "$.post(ajax_object.ajaxurl..."
What am I doing wrong?
Here's my HTML:
<button class="get_project" data-postid="3300">PROJECT NAME</button>
<div class="postcontainer"></div>
Here's my Javascript:
jQuery(function($){
$('.get_project').click(function() {
var postid = $(this).data('postid'); // Amended by #dingo_d
$.post(ajax_object.ajaxurl, {
action: 'my_load_ajax_content ',
postid: postid
}, function(data) {
var $response = $(data);
var postdata = $response.filter('#postdata').html();
$('.postcontainer').html(postdata);
});
})
//alert( "hello world" );
});
and here is the php from my functions.php file:
function my_load_ajax_content () {
$pid = intval($_POST['post_id']);
$the_query = new WP_Query(array('p' => $pid));
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$data = '
<div class="post-container">
<div id="project-content">
<h1 class="entry-title">'.get_the_title().'</h1>
<div class="entry-content">'.get_the_content().'</div>
</div>
</div>
';
}
}
else {
echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
}
wp_reset_postdata();
echo '<div id="postdata">'.$data.'</div>';
}
// Next two lines corrected - thanks #dingo_d
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
Also required in functions.php within the script enqueuing function:
wp_enqueue_script( 'myajaxpostloader', get_template_directory_uri().'/js/ajax.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'myajaxpostloader', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
(note that my Javascript is saved as /js/ajax.js where /js/ is a subdirectory of the Wordpress theme).
You didn't localize your ajax object. In Twenty fifteen theme you'd do it like this - in functions.php you'd put
wp_localize_script( 'twentyfifteen-script', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
Where your scripts are enqueued.
In your theme be sure to use proper handle - in stead of 'twentyfifteen-script' put the one where your ajax code is in. So if your ajax JavaScript is located in a file called custom.js, and you've enqueued that script with the handle custom_js, then you'd put
wp_localize_script( 'custom_js', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
After you've enqueued that script. All in all in your functions.php you'd put something like this:
add_action('after_setup_theme', 'mytheme_theme_setup');
if ( ! function_exists( 'mytheme_theme_setup' ) ){
function mytheme_theme_setup(){
add_action( 'wp_enqueue_scripts', 'mytheme_scripts');
}
}
if ( ! function_exists( 'mytheme_scripts' ) ){
function mytheme_scripts() {
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom.js', array( 'jquery'), '1.0.0', true );
wp_localize_script( 'custom_js', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
}
}
Or at the very least look for such code and just place the localization there :)

Yii's default ajax is not working

In my Yii application, Yii's default Ajax is not working. Also default Ajax validation is not working. Has this been an installation problem or any other problem. How to enable Yii's default Ajax.
In my controller,
public function actionCreate() {
$model = new Company;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Company'])) {
$company = Company::model()->findAll();
if (count($company) === 0) {
$model->attributes = $_POST['Company'];
$uploadedFile = CUploadedFile::getInstance($model, 'logo');
if (isset($uploadedFile)) {
$fileName = date('Ymdhis') . '_' . $uploadedFile->name; // $timestamp + file name
$model->logo = $fileName;
}
if ($model->validate()) {
if ($model->save()) {
if (isset($uploadedFile)) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
}
$this->redirect(array('create'));
}
}
} else {
Yii::app()->user->setFlash('error', 'Company details is already exists.');
}
}
$this->render('create', array(
'model' => $model,
));
}
In view page,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'company-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<div class="form-group">
<?php echo $form->label($model, 'company_name', array('class' => 'req')); ?>
<?php echo $form->textField($model, 'company_name', array('class' => 'form-control')); ?>
<?php echo $form->error($model, 'company_name', array('class' => 'school_val_error')); ?>
</div>
Please help me.
Thanks...
Yii has no default AJAX. This is a technology based on JavaScript language. By default Yii includes a jQuery library which provided some methods for easy manipulations with AJAX. If you want use it on your page, you should add this string:
Yii::app()->clientScript->registerCoreScript('jquery');
You can add this string to your main layout, for example into top of /views/layouts/main.php`

Chained selects in Wordpress via AJAX

I need to make two chained select inputs (country, city) in WP.
(all is in locations taxonomy, country is a main category and city is a subcategory)
in first select i listed all countries:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => 0 ) );
In second select i need only the cities depend on selected country
(without page refresh/submit, so with AJAX)
I need passing selected value from first select to php variable:
$whichCountry = AJAX RESPONSE HERE
Listing second select:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => $whichCounty) );
Please help me how to achieve this
i make same code but its not enough:
JS:
(function ($) {
$(document).ready(function () {
$(‘#first_select’).on(‘change’, function(){
$.post(
PT_Ajax.ajaxurl,
{
// wp ajax action
action: ‘ajax-inputtitleSubmit’,
// vars
data: $(‘#first-select’).val(),
// send the nonce along with the request
nextNonce: PT_Ajax.nextNonce
},
function (response) {
console.log(response.data);
}
);
return false;
});
});
})(jQuery);
PHP:
add_action( ‘wp_enqueue_scripts’, ‘inputtitle_submit_scripts’ );
add_action( ‘wp_ajax_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
add_action( ‘wp_ajax_nopriv_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
function inputtitle_submit_scripts() {
wp_enqueue_script( ‘inputtitle_submit’, get_template_directory_uri() . ‘/assets/js/inputtitle_submit.js’, array( ‘jquery’ ) );
wp_localize_script( ‘inputtitle_submit’, ‘PT_Ajax’, array(
‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
‘nextNonce’ => wp_create_nonce( ‘myajax-next-nonce’ )
)
);
}
function myajax_inputtitleSubmit_func() {
// check nonce
$nonce = $_POST[‘nextNonce’];
if ( ! wp_verify_nonce( $nonce, ‘myajax-next-nonce’ ) ) {
die ( ‘Busted!’ );
}
// generate the response
$response = json_encode( $_POST );
// response output
header( “Content-Type: application/json” );
$whichCountry = $response;
// IMPORTANT: don’t forget to “exit”
exit;
}
Functions.php
include_once(‘inputtitle_submit_inc.php’)

Adding wp_editor inside a thickbox

I would like to add a wp_editor inside a modal dialog (thickbox) at frontend but only gets an empty editor with no buttons on in. (WordPress 3.5 and plugin development)
The wp_editor is attached via an ajax call...
It seems like some important javascripts is missing to the page.
Is it possible to preload editor scripts i WP in some way?
Here is a sample plugin to expose the problem (adds a edit link to every content):
<?php
/*
Plugin Name: ThickboxEditor
*/
$thickboxeditor = new ThickboxEditor();
class ThickboxEditor{
function __construct()
{
add_action( 'wp_print_styles', array( &$this, 'wp_print_styles' ) );
add_action( 'init', array( &$this, 'init' ) );
add_filter( 'the_content', array( &$this, 'the_content' ) );
add_action( 'wp_ajax_thickboxeditor', array( &$this, 'editor' ) );
add_action( 'wp_ajax_nopriv_thickboxeditor', array( &$this, 'editor' ) );
}
function the_content( $content ){
$content .= 'EDIT THICKBOXEDITOR';
return $content;
}
function editor(){
wp_editor( $this->postcontent, 'postcontent', array(
'media_buttons' => false,
'teeny' => false,
'textarea_rows' => '7',
'tinymce' => array( 'plugins' => 'inlinepopups, fullscreen, wordpress, wplink, wpdialogs' )
) );
die(0);
}
}
?>
UPDATE
Thanks to #danielauener one solution is to initialize mceAddControl. So here is a working sample of the same plugin:
<?php
/*
Plugin Name: ThickboxEditor
*/
$thickboxeditor = new ThickboxEditor();
class ThickboxEditor{
function __construct()
{
add_action( 'wp_print_styles', array( &$this, 'wp_print_styles' ) );
add_action( 'init', array( &$this, 'init' ) );
add_filter( 'the_content', array( &$this, 'the_content' ) );
add_action( 'wp_ajax_thickboxeditor', array( &$this, 'editor' ) );
add_action( 'wp_ajax_nopriv_thickboxeditor', array( &$this, 'editor' ) );
add_action( 'wp_footer', array( &$this, 'wp_footer' ) );
}
function wp_footer(){
echo '<!--';
wp_editor( '', 'invisible_editor_for_initialization' );
echo '-->';
}
function the_content( $content ){
$content .= 'EDIT THICKBOXEDITOR';
return $content;
}
function editor(){
wp_editor( '', 'postcontent', array(
'media_buttons' => false,
'teeny' => false,
'textarea_rows' => '7',
'tinymce' => array( 'plugins' => 'inlinepopups, fullscreen, wordpress, wplink, wpdialogs' )
) );
?>
<script language="javascript">
jQuery(document).ready(function(){
tinymce.execCommand('mceAddControl',true,'postcontent');
});
</script>
<?php
die(0);
}
}
?>
It would be really nice to skip the ugly wp_editor initialization :-)
Funny, that thickbox doesn't provides any callbacks. But as I mentioned on twitter, I would try a $.ajaxSuccess call to solve the ugly js-inject. Just add the following to one of your javascript files:
(function($) {
// gets called for every successful ajax call
$(document).ajaxSuccess( function(evt, request, settings) {
// make sure this call was from your thickbox
if ($('#your-thickbox-selector').length > 0) {
tinymce.execCommand('mceAddControl',true,'postcontent');
}
});
})( jQuery );
UPDATE: The ajaxSuccess method has to be assigned to an element, changed the code

Resources