Support

Account

Home Forums ACF PRO How to get ACF data in ajax ?

Solved

How to get ACF data in ajax ?

  • Hi I’m trying to retrieve a custom ACF field using ajax. If I don’t use ajax I can easily recover the data, while with ajax it does not recover it. This is the code I used:

    In php file:

    add_action('wp_enqueue_scripts', function () { 
        wp_localize_script('affinita', 'affinita_obj', array('ajax_url' => admin_url('admin-ajax.php'), 'itemNonce' => wp_create_nonce("ajax_nonce"), 'p_url' => get_bloginfo('stylesheet_directory')));
    });
    
    add_shortcode('lista_segni_affinita', 'lista_segni_affinita_fn');
    
    function lista_segni_affinita_fn() {  
        ob_start();
        ?>   
         
          <div id="show_result_btn" class="btn"> Show result button </div>
             // result content 
          <div id="result"> </div>
    
        <?php
        $output = ob_get_clean();
        return $output;
    }
    
    function retrive_result () {    
       $result = get_field('caratteristiche_ariete', 'option');  //this is my acf option field.  
    }
    
    add_action('wp_ajax_nopriv_retrive_result', 'retrive_result');
    add_action('wp_ajax_retrive_result', 'retrive_result');

    here my .js code:

    if (!$) { $ = jQuery.noConflict(); }
    
     $(document).ready(function () {
          var templateUrl = affinita_obj.p_url;
         
          $('#show_result_btn').on( "click", function() {
             show_result_fn();
          });
    
         function show_result_fn() {
    
            $.ajax({
                url: affinita_obj.ajaxurl,            
                data: {
                   action: "retrive_result"
                },
                success: function (response) {
                    $("#result").append(response);
                },
                error: function (errorThrown) {
                    $("#result").append("error");
                }
              });
    
           }
       });

    can you help me? where am i wrong?

  • You are not returning anything from the ajax function usually it would look something like

    
    function retrive_result () {    
       $result = get_field('caratteristiche_ariete', 'option');  //this is my acf option field.  
       echo json_encode($result);
       exit;
    }
    
  • You do not return a value from function called in an AJAX request.

    You echo the value in the format that your success function is expecting.

    https://codex.wordpress.org/AJAX_in_Plugins

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.