skip to Main Content

I am using datatables in which I’ve implemented a <select> tag, I am trying to create a dependent dropdown but the problem is ajax returns only 0,

Also when I alert(data) in success function, the alert comes up with [object Object] reponse, not sure what’s going wrong.

For testing purpose I’ve putted the echo "<option value='test'>Test</option>";

$('#data-modification-table tbody').on('change', 'td select', function(e) {
  e.preventDefault();
  let $tr = $(e.target).closest('tr');

  $.ajax({
    type: "POST",
    url: ajaxurl,
    dataType: "json",
    data: {
      action: "send_dropdown_account_data",
      account_id: $tr.find('.user_account_name').val(),
      project_id: $tr.find('.user_project_name').val(),
    },
    success: function(data) {
      alert(data);
    },
    error: function(req, status, err) {
      console.log('Something went wrong', status, err);
    }
  });
});
add_action('wp_ajax_nopriv_send_dropdown_account_dat', 'update_modification_dropdown_options');
add_action('wp_ajax_send_dropdown_account_dat', 'update_modification_dropdown_options');    

function update_modification_dropdown_options()
{
  echo "<option value='test'>Test</option>";
  $output = ob_get_clean();
  wp_send_json_success($output);
  wp_die();
}

Inside inspect’s network option I can see this response for admin-ajax.php: {"success":true,"data":"0"}

In console there is no error or message.

2

Answers


  1. Instead of echoing the output you should just return an array of data instead directly to the wp_send_json_success method.

    E.g.

    $data = [
        'input' => '<option value="test">Test</option>',
    ];
    
    wp_send_json_success($data);
    

    https://developer.wordpress.org/reference/functions/wp_send_json_success/

    The response will be returned in that AJAX call as JSON.

    alert(data.input)

    Login or Signup to reply.
  2. You are missing action name in add_action();

    add_action('wp_ajax_nopriv_send_dropdown_account_data', 'update_modification_dropdown_options');
    add_action('wp_ajax_send_dropdown_account_data', 'update_modification_dropdown_options');
    

    Try this one in ajax function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search