skip to Main Content

I am attempting to send the contents of a form to WordPress plugin using Ajax. I have followed many tutorials and examples. None so far have applied.

PHP: [/wp-content/plugins/tr/trplugin.php]

function trplugin_SC_viewTR($atts) {
  wp_enqueue_script( 'wp-util' );
  wp_enqueue_script('jquery-ui-widget');
  wp_enqueue_script('jquery-ui-autocomplete');
  wp_enqueue_script('jquery-ui-button');
  wp_enqueue_script('trplugin-core',
    plugin_dir_url(__FILE__).'js/tr.js',
    array('jquery-ui-widget','jquery-ui-autocomplete','jquery-ui-button',),
    '0.0.1',
    TRUE
  );
  $wpAjax = array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce( 'trplugin-core' )
  );
  wp_localize_script('trplugin-core', 'wpAjax', $wpAjax );

}
add_shortcode('tr-view', 'trplugin_SC_viewTR');

function post_flagtr() {
    echo json_encode(array('123','abc'));
    wp_die();
}
add_action( 'wp_ajax_flag_tr', 'post_flagtr' );

Excerpt of Included JS File: [tr.js]

jQuery('#exampleDIV').append(
jQuery('<a id="trView_flagSUBMIT" class="makeButton">Submit Report</a>').on('click',function(event) {
    formDATA = jQuery('form#trView_flagFORM').find('input:visible,textarea:visible').serializeArray();
    postTHIS = [];
    formDATA.forEach(function(i) {
        postTHIS[i.name] = i.value;
    });
    postTHIS.action = 'flag_tr';
    postTHIS.nonce = wpAjax.nonce;
    console.log(postTHIS);
    console.log(wpAjax);
    
    tryTHIS = 1;
  if ( tryTHIS === 1 ) {
    jQuery.ajax({
      type : 'POST',
      dataType : 'json',
      headers: {
        'Content-Type':'application/x-www-form-urlencoded;'
      },
      url : wpAjax.ajax_url,
      data : postTHIS,
      success: function(response) {
        console.log(response);
        },
      error: function (jqXHR, textStatus, errorThrown) {
        console.log("errorThrown="+ errorThrown+", textStatus=" + textStatus, jqXHR);
      }
    });   
  } else if ( tryTHIS === 2 ) {
    jQuery.post(wpAjax.ajax_url, postTHIS, function(response) {
            console.log(response);
        }
    );
  } else if ( tryTHIS === 3 ) {
    wp.ajax.post('flag_tr', postTHIS).done(function(response) {
            console.log(response);
        }
    );
  } else if ( tryTHIS === 4 ) {
    fetch(wpAjax.ajax_url, {
        method: "POST",
        body: postTHIS,
    }).then((resp) => {
        console.log(resp);
    }).catch((resp) => {
        console.log(resp);
    });
  }
})
);

Any value of tryTHIS causes the same result, which is no HTTP post to the serer.

NOTE: trplugin-core is my work, and tr is redacted namespace, I am actually using a longer name in my code.

EDIT: Implementing FeniX’s suggestion [as in #1] results in:

errorThrown=Bad Request, textStatus=error, jqXHR=[object Object

and no error in the server log.

3

Answers


  1. Chosen as BEST ANSWER

    The problem is the line:

    postTHIS = [];
    

    It needs to be:

    postTHIS = {};
    

  2. Give it a try, the 1st type, but implement the ‘error:’ branch, to see your errors.
    (It can happen, that you might have to use JSON.stringify() functions for the data at some point.)

    error: function (jqXHR, textStatus, errorThrown)
          {
            console.log("errorThrown="+ errorThrown+", textStatus=" + textStatus + ", jqXHR=" + jqXHR);
          }
    
    Login or Signup to reply.
  3. Nice catch! Although the documentation states, that : (Data) Type: PlainObject or String or Array.
    Somewhat the array is converted and treated as a string kind differently. ( https://api.jquery.com/jquery.ajax/ )

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