Ajax Post Call in Admin-Ajax. Php Returns 0 with 400 Bad Request (Wordpress)

Hi as you can see I'm trying to send my data to admin-ajax.php using ajax post call kindly check the code below and the template that I use is betheme.

index.html

        $('#send-form').on('submit', function () {

            $.ajax({
                url : '<?php echo admin_url('admin-ajax.php'); ?>',
                data : {
                    'action' : 'test_func',
                    'data':'lorem ipsum'
                },
                type : 'POST',
                contentType: "application/json; charset=utf-8",
                dataType : 'json',
                success : function (callback) {

                    console.log(callback);
                }
            });

            return false;

        });

functions.php

function test_func () {
    echo json_encode(array('res'=>'return dummy text'));
}
add_action('wp_ajax_nopriv_test_func', 'test_func');
2

1 Answer

As per the code of ajax no need of adding contentType: "application/json; charset=utf-8 because you are passing data as string, so contentType property is not required.

To fix the issue of getting 0 every time you just have to add wp_die() at the end of test_func method.

Here you edited code

1) jQuery Ajax Code:

jQuery('#send-form').on('submit', function () {
        $.ajax({
            url : '<?php echo admin_url('admin-ajax.php'); ?>',
            data : {
                'action' : 'test_func',
                'data':'lorem ipsum'
            },
            type : 'POST',
            // contentType: "application/json; charset=utf-8",
            dataType : 'json',
            success : function (callback) {

                console.log(callback);
            }
        });

        return false;

    });

2) Code of functions.php

function test_func () {
    echo json_encode(array('res'=>'return dummy text'));
    wp_die();
}
add_action('wp_ajax_nopriv_test_func', 'test_func'); // ajax call for non-login user.
add_action('wp_ajax_test_func', 'test_func'); // ajax call for login user.
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest