Plugin Admin Page Ajax-Admin call returning 0, URL set correctly. Implemented localized scripts but did not fix it

I am attempting to submit an Ajax call transfer the source URL of a selected image from a WordPress Media Library to PHP

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);
    }
  });
});

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);
    }
  });
});
Share Improve this question edited Jul 2, 2019 at 1:32 Jacob Peattie 44.2k10 gold badges50 silver badges64 bronze badges asked Jul 2, 2019 at 1:28 peter kpeter k 54 bronze badges 3
  • 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/plugins/javascript/enqueuing/… – Jacob Peattie Commented Jul 2, 2019 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 Commented Jul 2, 2019 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 Commented Jul 2, 2019 at 4:57
Add a comment  | 

2 Answers 2

Reset to default 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();
}

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();
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745349652a4623752.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信