Ajax with sage-acf-wp-blocks

I use sage-acf-wp-blocks to create a gutenberg block. I enqueue a javascript file in it, like:

{{--
    ....
    EnqueueScript: scripts/landingform.js
    ....
--}}

I want to use ajax in front-end, so I need to use wp_localize_script, but I don not know the $handle parameter of the function.
I tried wp_localize_script('landingform', 'ajax_object', $ajax_params); and also changing 'landingform' to landingform.js or sage/landingform or sage/landingform.js, but non of them worked.
I always get: ReferenceError: ajax_object is not defined.

I write down here all the steps I made:
I created in app/ajax.php:

<?php

namespace App;

class Ajax
{
    public function __construct()
    {
        add_action('wp_ajax_landingform', [$this, 'handleLandingform']);
        add_action('wp_ajax_nopriv_landingform', [$this, 'handleLandingform']);

        add_action('wp_enqueue_scripts', function () {
            $ajax_params = array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'ajax_nonce' => wp_create_nonce('my_nonceika'),
            );

            wp_localize_script('landingform', 'ajax_object', $ajax_params);
        }, 
    }

    public function handleLandingform()
    {
        echo 'AJAX response here';
        wp_die();
    }
}

new Ajax();

Edited the resources/functions.php to include ajax.php:

array_map(function ($file) use ($sage_error) {
    $file = "../app/{$file}.php";
    if (!locate_template($file, true, true)) {
        $sage_error(sprintf(__('Error locating <code>%s</code> for inclusion.', 'sage'), $file), 'File not found');
    }
}, ['helpers', 'setup', 'filters', 'admin', 'ajax']);

Created resources/assers/scripts/landingform.js:

import $ from 'jquery';

$(function () {
  var fruit = 'Banana';

  // This does the ajax request
  $.ajax({
    // eslint-disable-next-line no-undef
    url: ajax_object.ajax_url,
    data: {
      action: 'landingform',
      fruit: fruit,
    },
    success: function (data) {
      // This outputs the result of the ajax request
      console.log(data);
    },
    error: function (errorThrown) {
      console.log(errorThrown);
    },
  });
});

Added it resouces/assets/config.json:

{
  "entry": {
      ....
      "landingform": ["./scripts/landingform.js"]
   },
...
}

I also checked how sage-acf-wp-blocks works, it uses a checkAssetPath function on the value of EnqueueScript :

function checkAssetPath(&$path)
{
    if (preg_match("/^(styles|scripts)/", $path)) {
        $path = isSage10() ? \Roots\asset($path)->uri() : \App\asset_path($path);
    }
}

Then checked \App\asset_path :

function asset_path($asset)
{
    return sage('assets')->getUri($asset);
}

Where function sage looks like:

function sage($abstract = null, $parameters = [], Container $container = null)
{
    $container = $container ?: Container::getInstance();
    if (!$abstract) {
        return $container;
    }
    return $container->bound($abstract)
        ? $container->makeWith($abstract, $parameters)
        : $container->makeWith("sage.{$abstract}", $parameters);
}

But here I’m completly lost, I can not understand this code… :confounded:
Any idea, how should I use wp_localize_script? @MWDelaney?

P.S.: If I put my JS in the main.js, and localize that, then it’s working.

Hi @Koli14

When you add your js script in config.json, are you register this script in setup.php ?

wp_enqueue_script(‘sage/landingform.js’, asset_path(‘scripts/landingform.js’), [‘jquery’], null, true);

?

No, because I think it’s done in the sage-acf-wp-blocks plugin. Because the script is there, it’s working, I can console.log from it. So I don’t want to enqueue it duplicated.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.