Remove entire [$key] from array stored in custom field using Ajax – unset($array[$key]); not working

Question

I’m looking to use Ajax to delete the key [1] from the following array which is stored in a custom user field and then re-save it…

I am trying to do this by using unset($array[$key]) then saving the updated values but without any success I’m afraid.

TYI for your help…

Array (

  [0] => Array (
    [dna_cal_when] => 1576926000
    [dna_cal_position_id] => 
    [dna_cal_candidate_id] => 
  )

  [1] => Array (
    [dna_cal_when] => 1576927800
    [dna_cal_position_id] => 
    [dna_cal_candidate_id] => 
  )

  [2] => Array (
    [dna_cal_when] => 1576929600
    [dna_cal_position_id] => 
    [dna_cal_candidate_id] => 
  )

) 

Here is the function…

add_action( 'wp_ajax_dna_nuke_diary_slots', 'dna_nuke_diary_slots' );

function dna_nuke_diary_slots() {

  $user   = $_POST['user']; 
  $stamp  = array($_POST['stamp']);

  // values for these two variables are retrieved from custom data attribute in following html and ajax call

  $stamps = !empty(get_user_meta( $user, 'dna_cal', true)) ? get_user_meta( $user, 'dna_cal', true) : array();
  $key    = array_search($stamp, array_column($stamps, 'dna_cal_when'));

  unset($stamps[$key]);

  $new_stamps   = $stamps;
  $sort_stamps  = array_values($new_stamps);

  update_user_meta( $user, 'dna_cal', $sort_stamps);

  wp_die();

}

FYI – following is the Ajax call and a sample of the HTML

$('.slot').on('click', 'a.booked', function(e) {
  e.preventDefault();

  var user   = $('#dna_day').attr( 'data-user' );
  var stamp  = $(this).attr( 'data-timestamp' );

  $(this).removeClass('booked').addClass('nuked');

  $.ajax({
    type: 'POST',
    url: ajax_object.ajaxurl,
    data: {
      action: 'dna_nuke_diary_slots',
      user: user,
      stamp: stamp
    }
  });

});


<div id="dna_day" class="dna-day" data-user="256">
  <div id="dna_slots" class="slots">
    <div class="slot"><a class="booked" data-timestamp="1576926000" href="#"></a></div>
    <div class="slot"><a class="booked" data-timestamp="1576927800" href="#"></a></div>
    <div class="slot"><a class="booked" data-timestamp="1576929600" href="#"></a></div>
  </div>
</div>
0
, , richerimage 2 years 2019-12-30T08:38:51-05:00 0 Answers 86 views 0

Leave an answer

Browse
Browse