Update WordPress JSON data via ajax

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:

Read More
<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');
              },
         });
    });

Related posts

2 comments

  1. 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

  2. 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

    <form id="todo-form">
      <?php
        $repeater = get_field( 'todo_list' );
          if ( ! $repeater ) {
            $repeater = array(
                array(
                    'todo_checkbox' => '',
                    'todo_item'  => '',
                    )
                );
            }
        ?>              
        <?php foreach ( $repeater as $k => $v ) : ?>
          <?php $checked = $v['todo_checkbox']; ?>
          <li>
            <input type="checkbox" class="todo-checkbox check" name="fields[todo_list][<?php echo absint( $k ); ?>][todo_checkbox]" value="1" <?php checked( $checked, true ); ?> />
            <input type="checkbox" class="todo-checkbox hide" name="fields[todo_list][<?php echo absint( $k ); ?>][todo_checkbox]" value="0"    <?php checked( $checked, false ); ?> />
            <p name="fields[todo_list][<?php echo absint( $k ); ?>][todo_item]" class="todo-item"><?php echo esc_attr( $v['todo_item'] ); ?></p>
         </li>
       <?php endforeach; ?>         
    </form>
    

    Jquery

    var form = "#todo-form";
    var wpajax = WP_API_Settings.root + 'wp/v2/client/'+post_id;
    $(form).change(function(event) {
      event.preventDefault();
      var checkbox = $('.todo-checkbox');
      var formData = checkbox.serialize();
      $.ajax({
        type:'POST',
        url: wpajax,
        dataType : 'json',
        beforeSend: function ( xhr ) {
            xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
        },
       data: formData,
       success: function(){
          console.log('success!');
      },
      error: function(){
          console.log('error');
      },
     });
     return false;
    });
    

Comments are closed.