Shirantha Shirantha - 1 year ago 117
Ajax Question

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.

Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.

I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.

But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?

I have the following code at the moment.


<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">

//Ajax Call

$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');

var adminAjaxRequest = function(formData, myaction) {
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
success: function(response) {
if (true === response.success) {
} else {

userSubmitButton.addEventListener('click', function(event) {
var formData = {
'name': document.getElementById('name').value

adminAjaxRequest(formData, 'data_submission');

And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.

function data_submission(){

wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );

Could not locate where the faulty is. Some help would be appriciated


Answer Source

First this is not a standard way to use ajax in wordpress, use wp_localize_script for embedding the global ajax_url variable,

 wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
    wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));

Now as url in ajax you can add my_ajax_url.ajax_url, this will send a request to admin-ajax.php.

Now coming to your question you are returning an wp_json_error so the result is 0, use this and return whatever data you wants in ajax success,

$responce['result'] = 1
wp_send_json( $response );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download