I'm cycling through an associative array and adding each child array as a row in a table.
The last column in that table is a button in which I want to use to remove that array from the parent array in the database.
Here's my markup:
<?php
$response_cost = get_post_meta( 379, '_wc_booking_pricing', true );
?>
<div id="response-cost" class="hidden"><?php echo json_encode( $response_cost); ?></div>
<?php
$i = 0;
foreach ($response_cost as $response) { ?>
<tr id="array-<?php echo $i; ?>">
<!-- table construction -->
<td><button class="remove-array" data-id="<?php echo $i; ?>"><i class="fa fa-times"></i></button></td>
</tr>
<?php
$i++;
};
?>
Here's my jQuery that takes care of removing the child array:
(function($) {
$(document).ready (function () {
$(function(){
var arrString= $('#response-cost').text();
const arr = JSON.parse(arrString);
$('.remove-array').click(function(){
var val = $(this).attr("data-id");
arr.splice(val, 1);
var arr_stringify = JSON.stringify(arr);
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
data:{
action: 'update_cost_rule_table_action',
stringified_arr: arr_stringify,
},
success: function( data ){
console.log( data );
}
});
});
});
});
}) (jQuery);
Here's the function in my function.php file:
add_action( 'wp_ajax_update_cost_rule_table_action', 'update_cost_rule_table' );
add_action( 'wp_ajax_nopriv_update_cost_rule_table_action', 'update_cost_rule_table' );
function update_cost_rule_table(){
$response_cost = json_decode($_POST['stringified_arr']);
update_field('_wc_booking_pricing', $response_cost, 379);
wp_die();
}
And here's how I'm enqueuing the script:
function gt21_scripts() {
wp_register_script( 'cost-rule', get_template_directory_uri() . '/js/cost-rule.js', array( 'jquery' ) );
wp_enqueue_script( 'cost-rule' );
wp_localize_script( 'cost-rule', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
};
add_action( 'wp_enqueue_scripts', 'gt21_scripts' );
I'm currently getting a 404 error for the admin-ajax.php in my console.
You write an incorrect file name.
Replace
admin_url( 'admin_ajax.php' )
With this
admin_url( 'admin-ajax.php' )