0

I am trying to get the content of an ACF field through an Ajax call. This is my callback function:

function my_ajax_request() {

      $id = $_POST['id'];

      if( have_rows('carousel_slide') ):

    // Loop through rows
    while( have_rows('carousel_slide') ) : the_row();

     // Load sub Fields
     $cta_text = get_sub_field('cta_text');

     // Allowed html
     $allowed_html = array(
       'strong' => array()
     );
    ?>

    <div class="cta-popup">
      <!-- Modal -->
      <div class="modal fade" id="cta-modal-1<?php echo $id; ?>" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <p><?php echo wp_kses( $cta_text, $allowed_html );?></p>
            </div>
          </div>
        </div>
      </div>
    </div>
<?php
   // End loop
   endwhile;
   // End if
 endif; ?>

</div><!-- end carousel-inner -->

<?php
die();
}
add_action( 'wp_ajax_my_ajax_request', 'my_ajax_request' );

And this is my Ajax call:


  jQuery('.btn').click(function () {
    var id = jQuery(this).attr('data-target').replace('#', '');
    console.log(id);
    jQuery.ajax({
        url: ajaxurl.url,
        type: 'POST',
        data: {
            action: 'my_ajax_request',
            id : id
        },
        success: function (result) {
           jQuery('.modal').attr('id',id);
           jQuery(id).modal('show');
           alert(id);
        },
        error: function () {
            alert("error");
        }
    });

});
});

The id comes from a button that when clicked should open a bootstrap modal. However, I keep getting the following notice:

Notice: Undefined index: my_id in /Applications/MAMP/htdocs/wordpress/wp-content/themes/my-teme/functions.php on line 61

The idea is to use the id from the Ajax call on my_ajax_request(). What am I missing?

3
  • Note that jQuery(id).modal('show'); won't work as you stripped the # out earlier. Your AJAX also directly inserts id into the HTML with no escaping, so if I make a request with the ID "><h1>Hello world</h1></body></html> the page will be trashed, or I could use it to insert script tags and launch attacks
    – Tom J Nowell
    Jan 26, 2021 at 11:23
  • Also have you considered using the newer REST API for your AJAX instead? Admin AJAX is an old and difficult API to use with many pitfalls and easy mistakes
    – Tom J Nowell
    Jan 26, 2021 at 11:24
  • Thanks. Will take a look into the REST API option.
    – Madeirense
    Jan 26, 2021 at 11:54

1 Answer 1

1

There are 2 problems:

Problem 1

Your AJAX endpoint looks for my_id:

      $id = $_POST['my_id'];

But your javascript sends id:

            id : my_id

Importantly:

id != my_id

They do not match. There is no $_POST['my_id'], that's why you get a PHP notice

Problem 2

You're using $_POST but the code does not make a POST request:

type: 'POST',

There is no type parameter, the jQuery docs say to use method: 'POST'


As a side note, a REST API endpoint would have complained that the required my_id parameter was missing, and it would have complained that no GET endpoint existed, making both problems super clear in human readable text.

Even if the AJAX endpoint starts working, consider migrating to a REST API endpoint, it will give you:

  • human readable error messages
  • dedicated fields for listing your parameters, who can access it, all implemented by WP Core so you know you didn't make a mistake or forget something
  • a pretty permalink URL
  • better authentication, and the option for remote API access with the use off additional plugins
  • easier to debug code
12
  • Yes, didn't realise that. Thank you. But even fixing that typo the issue persists.
    – Madeirense
    Jan 25, 2021 at 22:09
  • The php notice? Or something else? When you say you fixed the typo, how did you fix it? Please be more specific, and note that you asked why you get the PHP notice, not how to make your AJAX endpoint functional.
    – Tom J Nowell
    Jan 25, 2021 at 23:35
  • My bad. I apologise. I ensured the id on the Ajax matches the is on the callback but I still get the undefined index notice.
    – Madeirense
    Jan 26, 2021 at 0:36
  • can I see how you did that?
    – Tom J Nowell
    Jan 26, 2021 at 9:47
  • I have update my code above to reflect the changes I have made. Still no luck though. I keep getting Undefined notice: id
    – Madeirense
    Jan 26, 2021 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.