datatables ajax jnvalid json response when using ajax option with binary

When attempting to switch Datatables to use binary JSON, the ajax option to Datatables construction was added as per below, but error message “Invalid JSON response” is outputted on load of data-tables. Any ideas how to resolve?

 "ajax": {
                    "url": "fetchtabledata.do?" + "instance=<c:out value="${resultsBean.instance}"/>",
                    "dataType": "binary",
                    "dataSrc": function ( json ) {
                        return Smile.Parser.parse(json);
                    }
            }, 

functions – Ajax Form Issues using Lightsail (AWS)

I am having issues with a contact form using Ajax and jQuery.

I followed this guide: https://www.youtube.com/watch?v=LYvx_L9ESn0, and it works on my local server (Laragon), by that laragon catches the email being sent to me.

But using the contact form in my live server doesn’t seem to send the form to my admin_email. I already made sure the admin email of my wordpress site is my own email address.

Here is the code for the form (jQuery and Ajax only, no HTML):

<script>
    (function($) {
        $('#FormControlSelectService').change(function() {
            // Shows the Online Program Options if Online Training is chosen
            ($(this).val() == 'Online' ? $('#OnlineSelectProgram').show() : $('#OnlineSelectProgram').hide());
        });

         

        $('#enquiry').submit( function(event) {
            event.preventDefault(); // Allows the event to be cancelled if it is cancelable

            var endpoint = '<?php echo admin_url('admin-ajax.php'); ?>';
            var form = $('#enquiry').serialize(); // Serializes all the data entered
            var formdata = new FormData;

            formdata.append('action', 'enquiry');
            formdata.append('nonce', '<?php echo wp_create_nonce('ajax-nonce');?>');
            formdata.append('enquiry', form);

            $.ajax(endpoint, {
                type: 'POST',
                data: formdata,
                processData: false,
                contentType: false,

                success: function(res) {
                    $('#enquiry').fadeOut(200);
                    $('#success_message').text('Thank You for Your Enquiry').show();
                    $('#enquiry').trigger('reset');
                    $('#enquiry').fadeIn(500);
                },

                error: function(err) {
                    alert(err.responseJSON.data);
                }
            })
        });

    })(jQuery) </script>

And the code for it in my functions.php:

add_action('wp_ajax_enquiry', 'enquiry_form');
    add_action('wp_ajax_nopriv_enquiry', 'enquiry_form');
    /**
     * 
     * Ajax Form
     */
    function enquiry_form() 
    {
        if (!wp_verify_nonce($_POST('nonce'), 'ajax-nonce')) {
            wp_send_json_error('Nonce is incorrect', 401);
            die();
        }

        $formdata = ();
        wp_parse_str($_POST('enquiry'), $formdata);

        // Sending the Email
        $admin_email = get_option('admin_email');

        // Email Headers
        $headers() = 'Content-Type: text/html; charset=UTF-8';
        $headers() = 'From: My Website <' . $admin_email . '>';
        $headers() = 'Reply-to: ' . $formdata('email');

        // Sending Email To
        $send_to = $admin_email;

        // Subject
        $subject = "Enquiry from " . $formdata('fname') . ' ' . $formdata('lname');

        // Message
        $message = '';

        foreach($formdata as $index => $field)
        {
            $message .= '<strong>' . $index . '</strong>: ' . $field . '<br/>';
        }

        try {
            if (wp_mail($send_to, $subject, $message, $headers)) {
                wp_send_json_success('Email Sent!');
            } else {
                wp_send_json_error('Email Error');
            }
        } catch (Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }

template – Magento 2 Knockout bind on ajax response

I am going crazy with knockout on Magento 2, I am new to knockout and I cannot understand what I am doing wrong. I know there are some related questions posted there but each one is different from what I need. I checked all questions posted before, all links on google, still cannot understand why is not working.

I am trying to retrieve the shipping data on product page on Magento 2 and append them with foreach inside template.

That is what I have until now:

calculate.js

define((
    'jquery',
    'mage/translate',
    'mage/storage',
    'mageUtils',
    'uiComponent',
    'ko'
), function (
    $,
    $t,
    storage,
    utils,
    Component,
    ko
) {

    return Component.extend({

        defaults: {
            carrier: null
        },
        initialize: function (config) {
            var self = this;
            this._super();
            this.carrier = ko.observable();
            this.carrier_f(this.sku);
            return this;
        },
        carrier_f: function (sku) {
            var address;
            var postcode;
            var myViewModel;
            var carrier_view = {};

            var serviceUrlCreate, serviceUrl, payload;
            /**
             * Save  values .
             */
            serviceUrl = '/rest/V1/working_function/' + sku;
            payload = JSON.stringify({
                    address: {
                        'city': '',
                        'region_id': '569',
                        'country_id': 'US',
                        'postcode': '',
                    }
                }
            );
            storage.post(
                serviceUrl,
                payload
            ).done(function (response) {
                this.carrier = ko.observable();

                var carrier_view = {
                    'carrier': this.response
                };


                ko.cleanNode($('#shipping_results')(0));
                ko.applyBindings(carrier_view, $('#shipping_results')(0));

                console.log(response);

            }).fail(function (response) {
                console.log(response);
            });

        },

        checkShipping: function () {

            console.log(this.sku);
            
            this.carrier_f(this.sku);
        }
        
    });
    
});

form.phtml

<div data-bind="scope: 'shipping_estimate'">
    <ul id="shipping_results" data-bind="foreach: carrier">
        <li>
            <span data-bind="text: carrier_title"></span>
        </li>
    </ul>
</div>
    <button data-bind="click: checkShipping" class="btn-estimate">Check</button>

    <script type="text/x-magento-init">
                                       {
                                          "*": {
                                                  "Magento_Ui/js/core/app": {
                                                         "components": {
                                                             "shipping_estimate": {
                                                                  "component": "Vendor_Name/js/calculate",
                                                                  "sku": "<?= $block->getProduct()->getSku(); ?>"
                                                              }
                                                         }
                                                   }
                                             }
                                        }                                  
    </script>

Ajax Response is like that:

enter image description here

So basically I need to get results on page load and also when click the Check Button (I will add some textbox after), but now there are not results inside, just empty response.

I tried everything, but still not found a solution, the only thing seems working is to change the scope to “anything-else”, then the foreach is working, but the click event is not called.

If anyone has the patience to explain me what I am doing wrong I would really appreciate it. Thank you

woocommerce – Trying to run a add_action within a function to run a woocomerce function on a ajax request

I am able to get a ajax request to work properly on a woocommerce checkout form page, now I want to update the price of the checkout in that ajax request. My add_action is in the function that is fired by the ajax request.

This is all done in a custom plugin as well

Here is my code this far, it doesn’t seem like the function request_gift_card ever fires


function gift_card_redeem(){
  
  if(!empty($_SERVER('HTTP_X_REQUESTED_WITH')) && strtolower($_SERVER('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest') {
    error_log("test !empty");
    
    add_action( 'woocommerce_before_calculate_totals', 'request_gift_card', 99 );

    function request_gift_card($cart_object){
      if( !WC()->session->__isset( "reload_checkout" )) {
          /* Gift wrap price */
          $additionalPrice = 5;
          error_log($cart_object);
          foreach ( $cart_object->cart_contents as $key => $value ) {
              if( isset( $value("embossing_fee") ) ) {
                  // Turn $value('data')->price in to $value('data')->get_price()
                  $orgPrice = floatval( $value('data')->get_price() );
                  $discPrice = $orgPrice + $additionalPrice;
                  $value('data')->set_price($discPrice);
              }
          }
      }
    }

    $result('type') = "success";
    $result = json_encode($result);
    echo $result;
  }
  else {
    error_log("test else");
      header("Location: ".$_SERVER("HTTP_REFERER"));
  }

  die();
}

ajax – Woocommerce custom webhook -> action woocommerce_before_calculate_totals

I want to create a custom webhook in woocommerce. I have done something like this before, but can’t remember the syntax and am having trouble finding it in the docs.

I have a custom plugin with the following code

function add_new_webhook_topics( $topics ) {
    // New topic array to add to the list, must match hooks being created.
    $new_topics = array( 
        'order.gift_card' => __( 'Order Gift Card', 'woocommerce' ),
        );
    return array_merge( $topics, $new_topics );
 }
 add_filter( 'woocommerce_webhook_topics', 'add_new_webhook_topics' );

I want to replace the Order Gift Card Section with a redeem gift card, now I assume the ‘order.gift_card’ is my topic which is supposed to fire on submission of payment. What I am actually wanting to do is fire a ajax function before submitting the payment which updates the checkout price with woocommerce_before_calculate_totals function.

Now I am debating if I am supposed to create a custom webhook which fires on a new form on the checkout page, which updates the total price before paying based on my returning payload from the webhook. Or I just do a Ajax request without tying into woocomerce webhooks since it is not an event based on woocommerce which fires the request I am trying to make.

Feel free to ask questions for clarification.

This is a previous post for context, with what landed me here
Is it possible to update the total price on the checkout page in woocommerce from a custom field

Woocommerce error on admin ajax search product: Unknown column ” in ‘where clause’

When I want to add products to a manual order in Woocommerce, the product search returns “no matches found”. I looked at the logs and I found this error seems to be culprit. I searched the error but every case I found, the unknown column name is defined in the log. Here it’s blank: Unknown column '' How can I investigate what’s causing it? I’m trying with TwentyTwenty and only WC activated…

Full error:
(proxy_fcgi:error) (pid 3178592) (client *:60140) AH01071: Got error 'PHP message: WordPress database error Unknown column '' in 'where clause' for query SELECT DISTINCT posts.ID as product_id, posts.post_parent as parent_id FROM wp_posts postsnttt LEFT JOIN wp_wc_product_meta_lookup wc_product_meta_lookup ON posts.ID = wc_product_meta_lookup.product_idnttt LEFT JOIN wp_wc_product_meta_lookup parent_wc_product_meta_lookupnttt ON posts.post_type = 'product_variation' AND parent_wc_product_meta_lookup.product_id = posts.post_parent ntttWHERE posts.post_type IN ('product','product_variation')nttt AND ( ( ( posts.post_title LIKE '%chorizo%') OR ( posts.post_excerpt LIKE '%chorizo%') OR ( posts.post_content LIKE '%chorizo%' ) OR ( wc_product_meta_lookup.sku LIKE '%chorizo%' ) OR ( wc_product_meta_lookup.sku = "" AND parent_wc_product_meta_lookup.sku LIKE '%chorizo%' ) )) nttt AND posts.post_status IN ('private','publish') ntttntttORDER BY posts.post_parent ASC, posts.post_title ASCnttt LIMIT 30 nttt made by do_action('wp_ajax_woocommerce_json_search_products_and_varia...',

actions – do_action won’t work in ajax callback

I want to perform some actions when ajax tasks done successfully. For instance, if the item added to the cart, I want to send an email. Also may perform a few more actions.

Setting up do_action('prefix_item_added_to_cart', $args); doesn’t recognized and so add_action doesn’t perform a task, in my case sending email.

If I write code procedural code to send an email, that works fine but using do_action.

Does not work

// ajax callback function
function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // perform action
        do_action('prefix_item_added_to_cart', $args);
    }
    ...

}

// action callback
function send_email_to_user($args) {

    // send email notification
    wp_mail('set params for email');

}

// action
add_action('prefix_item_added_to_cart', $args);

Works

function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // send email notification
        wp_mail('set params for email');
    }
    ...

}

8 – How to recenter a geolocation google common map in views after an ajax boundary filter execution?

On Drupal 8.97 with all updated modules, I have a View that uses a Geolocation Google Common Map as an attachment. The map acts a boundary filter, but after the filter executes Drupal.ajax(ajaxSettings).execute() via /modules/contrib/geolocation/modules/geolocation_google_maps/js/geolocation-common-map-google.js, I am unable to re-center the map to ANY coordinates, including the user’s location.

Before the ajax call, map.getCenter() works, and so does manually inputting coordinates, like map.getCenter({ lat: -34.397, lng: 150.644 }), but afterwards, no dice. The custom re-center buttons I created still register clicks, and if console.log the map object afterwards, I can’t see any changes to the map object…and indeed some of my other custom map controls (like zoom in and out) still work after the ajax execution. I’m baffled.

I have looked at the ajaxSettings object too, and have attempted to change some of those center related properties before executing the Drupal.ajax(ajaxSettings).execute() command as above, but I still can’t get the map center to change (though I don’t quite know if I’m looking at the right properties…there’s hundreds of them). The map can still be panned around with a mouse of course, but I ultimately would like for users to be able to re-center to their location…and I would like to programmatically recenter and execute a search using the center of city locations without having to reload the page, so it’s kind of critical that I get this sorted.

Thank you in advance for your help.

8 – Creating a route that returns an AJAX Response that opens a modal

​I have this route that is suppose to render a block and two view blocks and then display them in a modal.

Originally, I had this route created in the Pages section of Structure, but then decided to create it in my module using this tutorial

However, when I construct it in my module, now it won’t open in a modal. It attempts to, but then just fails with no errors in the console or in Drupal, so I can’t debug the issue because I can’t even find out what the issue is… If I go to the route directly in the browser instead of through a link, it just prints out an array of command objects

Here’s my code:

my_module.routing.yml

my_module.my.results:
  path: "/user/results"
  defaults:
    _title: "My Results"
    _controller: 'Drupalmy_moduleControllerme3Controller::myResults'
  requirements:
    _user_is_logged_in: "TRUE"
    _is_ajax_request: 'TRUE'

myController.php

class myController extends ControllerBase {
  function myResults() {
    $renderer = Drupal::service('renderer');

    $top_careers_view = views_embed_view('top_careers', 'block_top_careers');
    $top_careers = $renderer->render($top_careers_view);
    $matched_degrees_view = views_embed_view('matched_degrees', 'block_matched_degrees');
    $matched_degrees = $renderer->render($matched_degrees_view);

    $content = $top_careers . $matched_degrees;

    $title = "Title";
    $options = (
      'dialogClass' => 'my_modal'
    );
    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

    return $response;
  }
}

my-template.html.twig

<a 
  class="use-ajax"
  data-dialog-type="modal" 
  data-dialog-options='{
    "dialogClass": "my-modal"
  }'
  href="/{{ language }}/my/results">{{ 'Match More Careers'|t }}
</a>

At one point I had /my/results_test created in Pages that I would open up in a modal via the html link:

<a 
  class="ytp-magenta-button use-ajax"
  data-dialog-type="modal" 
  data-dialog-options='{
    "dialogClass": "ytp-dashboard-me3-modal"
  }'
  href="/{{ language }}/my/results_test">{{ 'Match More Careers'|t }}
</a>

I also had the /my/results route still created in my module and if I created a modal-link (defined above) to it from one of the blocks in /my/result_test, then the /my/results route would open in a modal as expected.

So essentially, with what I have, I can open my modal route from another modal, but I can’t open it directly from a regular page…

Intermittent AJAX error on Commerce Product pages causing pricing not to update when variations are changed

We have a Commerce 2 website with an intermittent where changing the variations on the add to cart form does not update the photos and prices. When the issue is occurring there is an AJAX error in the console log (see below). However, the error and issue disappear after a page-load of two.

JS aggregation is disabled and there is no other caching occurring on the site. I have no iead why AJAX fails sometimes. The error only occures on Product pages. Any ideas?

Uncaught Object { message: “nAn AJAX HTTP error occurred.nHTTP
Result Code: 200nDebugging information follows.nPath:
/products/reflection-plaque?ajax_form=1nStatusText: OKnResponseText:
nReflection
Plaquen!function(f,b,e,v,n,t,s)n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?nn.callMethod.apply(n,arguments):n.queue.push(arguments)};nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version=’2.0′;nn.queue=();t=b.createElement(e);t.async=!0;nt.src=v;s=b.getElementsByTagName(e)(0);ns.parentNode.insertBefore(t,s)}(window,document,’script’,n’https://connect.facebook.net/en_US/fbevents.js’);nfbq(‘init’,
‘1323570227846169’); nfbq(‘track’, ‘PageView’);nwindow.purechatApi =
{ l: (), t: (), on: function () { this.l.push(arguments); } };
(function () { var done = false; var script =
document.createElement(‘script’); script.async = true; script.type =
‘text/javascript’; script.src =
‘https://app.purechat.com/VisitorWidget/WidgetScript’;
document.getElementsByTagName(‘HEAD’).item(0).appendChild(script);
script.onreadystatechange …”, name: “AjaxError”, stack:
“@https://DOMAIN.com/core/misc/ajax.js?v=8.9.1:100:32n@https://DOMAIN.com/core/misc/ajax.js?v=8.9.1:644:3n”
} ajax.js:100:32