I'm trying to create a post from the front-end using WP Ajax but getting a 400 Bad Request error.
The data is coming from a server API response. What I'm trying to achieve is to save the JSON data I'm getting from the API response into a WP POST using Ajax. I know that there are lots of similar questions here in StackOverflow and Google Search and I already tried all of the solutions but still can't solve mine. I'm literally trying to solve this by just doing research for about 12 hours but still no luck.
Below is my current code:
PHP:
add_action( 'wp_enqueue_scripts', 'invicta_uploadpage_enqueue_scripts_styles', 5 );
function invicta_uploadpage_enqueue_scripts_styles() {
// AJAX JS
wp_enqueue_script(
'dropzone-config',
get_stylesheet_directory_uri() . '/lib/assets/dropzonejs/dropzone.config.js',
array('jquery')
);
wp_localize_script(
'dropzone-config',
'dropzoneconfigajax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
// Creating Ajax call
function vc_create_post() {
$fileid = $_POST['uploadfileid'];
$filename = $_POST['uploadfilename'];
$filesize = $_POST['uploadfilesize'];
$post_id = wp_insert_post( array(
'post_title' => $filename,
'post_content' => 'Download ' . $filename,
'post_status' => 'publish',
'post_author' => '1',
'comment_status' => 'closed',
'meta_input' => array(
'fileid' => $fileid,
'filesize' => $filesize,
)
));
if ( $post_id != 0 ) {
// success. do something.
} else {
// failed. say something.
}
die();
}
add_action( 'wp_ajax_vc_createpost_ajax', 'vc_create_post' );
add_action( 'wp_ajax_nopriv_vc_createpost_ajax', 'vc_create_post' );
JS dropzone.config.js
:
jQuery(document).ready(function($){
function createPost(fileID, fileName, fileSize) {
$.ajax({
url: dropzoneconfigajax.ajaxurl,
type: 'POST',
data: {
action: 'vc_createpost_ajax',
uploadfileid: fileID,
uploadfilename: fileName,
uploadfilesize: fileSize
},
success: function(data, textStatus, XMLHttpRequest) {
console.log('post succesfully created! Data: ' + data )
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
});
The value of fileID
, fileName
, fileSize
will be coming from another ajax call which is a server response after a file upload. ex: createPost(json.result.id, json.result.name, json.result.size);
Edit: I would also like to note that I'm implementing it on a WP Child Theme and not as a plugin and on a custom page template (Genesis Framework).
source https://stackoverflow.com/questions/71215795/wordpress-ajax-and-wp-admin-admin-ajax-php-400-bad-request-error
No comments:
Post a Comment