I am using the WP Rest API plugin and the ACF to REST API plugin along with Advanced Custom Fields. I have a repeater set up with 2 checkboxes and a text field. I am able to update the checkboxes in the database via a submit button but want to be able make the update via ajax, so when a user changes the checkbox, it is updated in the database. I feel like I am missing something basic for the change but nothing is happening. I’m not getting any errors, but the database is not updated. When I console.log data, I see everything there. This is my first go at ajax and I feel like I am really close!
HTML:
<form id="todo-form">
<div class="todos-list"></div>
</form>
<script>
var post_id = '<?php echo the_ID(); ?>';
</script>
jQuery:
var ajaxURL = 'http://'+window.location.host+'/wp-json/wp/v2/client/'+post_id;
$.getJSON(ajaxURL, function(data) {
console.log(data);
var output = '<ul class="todo-list">;
$.each(data.acf.todo_list, function(key, val){
if(data.acf.todo_list[key].todo_checkbox == true)
checked = 'checked';
} else {
checked = '';
}
output += '<li>';
output += '<input type="checkbox" class="todo-checkbox check" name="fields[todo_list]['+ key +'][todo_checkbox]" value="1" '+checked+' />';
output += '<input type="checkbox" class="todo-checkbox hide" name="fields[todo_list]['+ key +'][todo_checkbox]" value="0" />';
output += '<textarea name="fields[todo_list]['+ key +'][todo_item]">'+ data.acf.todo_list[key].todo_item +'</textarea>';
output += '</li>';
});
output += '</tbody></table>';
$('.todos-list').html(output);
//AJAX
var form = "#todo-form";
$(form).change(function(event) {
event.preventDefault();
var formData = JSON.stringify(data.acf.todo_list);
$.ajax({
type:'POST',
url: ajaxURL,
dataType : 'json',
data: formData,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
},
success: function(){
console.log('success');
},
error: function(){
console.log('error');
},
});
});
By default the WordPress REST API does not handle custom meta, you have to create a custom field and attach functions to save / get the data. Have you set that up?
If not check out the docs on extending
I was able to get it work by not using $.getJSON() and a little help from the plugin issues thread.
Updated code below:
HTML & PHP
Jquery