I'm having some trouble while I'm making an upload plugin. I'm using ajax to do the upload, but during the first test I get a 400 bad request error. Is there a fix for this?

Here is the js code


    $('#process-upload').on('click', function(e){
      var data = new FormData();
      data.append('file', $('#imageFile').prop('files')[0] );
      data.append('action', 'new_message');
      data.append('message', $('#imageMessage').val());

        url: wpu.ajaxurl,
        type: 'POST',
        contentType: false,
        processData: false,
        data: data,
        success: function(response){



and this is the php:

public function __construct()
    add_shortcode( 'upload-form', array($this, 'upload_form') );
    add_action( 'wp_enqueue_scripts', array($this, 'main') );
    add_action( 'admin_ajax_new_message', array($this, 'process_upload') );
    add_action( 'admin_ajax_nopriv_new_message', array($this, 'process_upload') );

  public function main()
    wp_enqueue_script( 'ajax-upload', plugins_url( 'ajax-upload.min.js' , __FILE__), array('jquery'), null );
    wp_localize_script( 'ajax-upload', 'wpu', array(
        'ajaxurl' => admin_url('admin-ajax.php')


  public function upload_form( $attr, $content = null )
      <form method="POST" enctype="multipart/form-data">
        <div class="custom-file">
          <input type="file" class="custom-file-input" id="imageFile" accept="image/*">
          <label class="custom-file-label" for="imageFile">Choose file</label>
        <textarea class="form-control" id="imageMessage" name="message"></textarea>
        <button type="button" class="btn btn-outline-secondary" id="process-upload"><?php _e('Save'); ?></button>
        <button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
    return ob_get_clean();

  public function process_upload()
    $file = array(
      'name' => $_FILES['imageFile']['name'],
      'type' => $_FILES['imagefile']['type'],
      'tmp_name' => $_FILES['imageFile']['tmp_name'],
      'size' => $_FILES['imageFile']['size'],
      'error' => $_FILES['imageFile']['error'],

    $upload = wp_handle_upload( $file , array( 'test_form' => false ) );


  • 1
    the hooks starts with wp_ajax_... and not admin_ajax_.... – Kaperto Jan 6 at 13:01

Your action should be wp_ajax and wp_ajax_nopriv instead of admin_ajax.

 add_action( 'wp_ajax_new_message', array($this, 'process_upload') );
 add_action( 'wp_ajax_nopriv_new_message',array($this, 'process_upload') );
  • 1
    Thanks, It was a mistake I made due this is my first time that I use ajax with wordpress – sialfa Jan 6 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.