0

I am attempting to submit an Ajax call transfer the source URL of a selected image from a WordPress Media Library to PHP in my plugin settings page. Upon clicking save I'm constantly met with "error, bad request". Status 400 when attempting to call my AJAX URL.

My AJAX URL is currently domain/wp-admin/admin-ajax.php which does indeed exist. I have tried setting multiple data types that the AJAX call should expect but I'm met with the same error.

If I remove the URL portion of the AJAX call in the javascript, it does lead to the success function, but the parameter for success, "response" consists of the HTML for the page and not the data I wish to transfer.

The HTML

<form method='post'>
  <div class='image-preview-wrapper'>
    <img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' height='100'>
  </div>
  <input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
  <input type='hidden' name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>
  <input type="submit" name="submit_image_selector" value="Save" id="saveMediaButton" class="button-primary">
</form>

Loading in the Javascript through enques

function enqueue_my_scripts() {

  wp_enqueue_script( 'media-library', plugins_url( '/media-library.js', __FILE__ ), array(), '1.0.0', true );

  wp_localize_script( 'media-library', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}

add_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );

The JavaScript that is called upon the button click ID'ed submitMediaButton

$('#saveMediaButton').click(function(e) {
  e.preventDefault();
  $.ajax({
    type: "POST",
    dataType: "html",
    url: my_ajax_object.ajax_url,
    data: {
      image_attachment_id: document.getElementById("image-preview").getAttribute('src')
    },
    success: function(response) {
      var jsonData = response;
      console.log(response);
      console.log(document.getElementById("image-preview").getAttribute('src'));
    },
    error: function(jqxhr, textStatus, errorThrown) {
      console.log(my_ajax_object.ajax_url);
      console.log(jqxhr);
      console.log(textStatus);
      console.log(errorThrown);
    }
  });
});
  • What's your code for handling the request? admin-ajax.php is going to return a 400 unless you hook something into a wp_ajax_ or wp_ajax_nopriv_ hook and pass action in your request data. See developer.wordpress.org/plugins/javascript/enqueuing/… – Jacob Peattie Jul 2 at 1:34
  • I'm confused as to where I'd fit this into my code, I would hook just any function into the wp_ajax hook? – peter k Jul 2 at 4:37
  • Well presumably you want something to happen when the ajax request is submitted, so you need to write the function for handling that request and hook into into those hooks, yes. – Jacob Peattie Jul 2 at 4:57
0

Hi please try below code

jquery :

$('#saveMediaButton').click(function(e) {
    e.preventDefault();

    $.ajax({
        url         : my_ajax_object.ajax_url,
        type        : 'post',
        data        : {
            action              : 'action_upload_img',
            image_attachment_id : document.getElementById("image-preview").getAttribute('src')
        },
        dataType    : 'html',
        success     : function( response ) {

            var jsonData = response;
            console.log(response);
            console.log(document.getElementById("image-preview").getAttribute('src'));

        },
        error       : function(jqxhr, textStatus, errorThrown) {
            console.log(my_ajax_object.ajax_url);
            console.log(jqxhr);
            console.log(textStatus);
            console.log(errorThrown);
        },
    });

});

PHP Code :

add_action( 'wp_ajax_action_upload_img', 'action_upload_img' );
add_action( 'wp_ajax_nopriv_action_upload_img', 'action_upload_img' );
function action_upload_img(){

    $response               = [];
    $response['data']       = $_POST;

    //Your code
    update_option( 'media_selector_attachment_id', $_POST["image_attachment_id"] ); 

    wp_send_json( $response );
    wp_die();
}
  • This was a great help, but if I were to try and update a plugin option with the AJAX callback, how would I go about this? update_option( 'media_selector_attachment_id', $response['data']["image_attachment_id"] ); Doesn't seem to work in the AJAX callback – peter k Jul 2 at 18:24
  • @peterk please check above edited code. – Milan Hirpara Jul 3 at 9:02
-1

Please try this :

add action parameter in data.

data: {
      action:"this_ajax_action",image_attachment_id: document.getElementById("image-preview").getAttribute('src')
    },

add in functions.php

add_action( 'wp_ajax_this_ajax_action', 'this_ajax_action_callback' );
add_filter( 'wp_ajax_nopriv_this_ajax_action', 'this_ajax_action_callback');
function this_ajax_action_callback()
{
    if(isset($_POST["image_attachment_id"]) && !empty($_POST["image_attachment_id"]));

     # here what you want to do with attachment id
     $data = "";

      echo $data;
      die();
}
  • please let me know what the wrong with my answer. why somebody did downvoted my answer ? tell me so i can improve my mistake. thank you! – Chetan Vaghela Jul 2 at 5:24

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.