0

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.

Daryl Lyn
  • 1
  • 1

3 Answers3

0

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);
      }
FeniX-
  • 3
  • 3
  • Results: errorThrown=Bad Request, textStatus=error, jqXHR=[object Object] – Daryl Lyn Mar 07 '21 at 22:00
  • You can go further by investigating the jqXHR object. Maybe try: `console.log("jqXHR obj=' , jqXHR); ` ( not "+", but " , " ) You can also try to add: `contentType: "application/json; charset=utf-8", ` to the original request. Investigate it in the browser by invoking the "Developer tools (F12 key) and 'network tab'" – FeniX- Mar 08 '21 at 10:23
  • Here are the possibilities, you can do with the jqXHR object: https://api.jquery.com/jQuery.ajax/#jqXHR – FeniX- Mar 08 '21 at 10:29
  • Which properties would be most useful? Expanding the entire object looks to be kinda big as a string... PS, thanks for the jqXHR link. :) – Daryl Lyn Mar 08 '21 at 17:50
  • Maybe, these fields: readyState, responseXML and/or responseText ..., status, statusText (may be an empty string in HTTP/2) – FeniX- Mar 08 '21 at 19:19
  • Give it a try, that what happens, when you send a fairly simple string with the request for data. Like ``` lang-js postTHIS.action = 'flag_tr'; postTHIS.nonce = wpAjax.nonce; postTHIS.key = 'value'; ``` – FeniX- Mar 08 '21 at 19:23
  • OFF: My markdowns don't work very well... i hope, you can figure it out anyways, what i was trying to write. – FeniX- Mar 08 '21 at 19:30
  • No worries on markup. Results: readyState: 4 responseText: "0" responseXML: undefined status: 400 statusText: "Bad Request" – Daryl Lyn Mar 08 '21 at 20:16
  • Is there a way to PM? I would give you a link to the DEV server, I just don't need the entire internet hitting our DEV server... – Daryl Lyn Mar 08 '21 at 20:35
  • I'm afraid not. Searching through stackoverflow, you can find similar cases, for example, like: https://stackoverflow.com/questions/16017081/getting-400-bad-request-error-in-jquery-ajax-post . Have you tried to stringify the JSON data? / Try it first with a very simple data, only with the 'action', and some other field, like i mentioned earlier (key1 => value1, or that kind of stuff) – FeniX- Mar 08 '21 at 21:06
0

The problem is the line:

postTHIS = [];

It needs to be:

postTHIS = {};
Daryl Lyn
  • 1
  • 1
0

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/ )

FeniX-
  • 3
  • 3