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);
}
});
});
wp_ajax_
orwp_ajax_nopriv_
hook and passaction
in your request data. See developer.wordpress.org/plugins/javascript/enqueuing/…