skip to Main Content

I tried several solutions that I found on Google/Stack Overflow like adding die() at the end of the function, echo true etc., but none of them worked. The function should be simple. Don’t know what the problem is. So here are the details:

My HTML FORM

<form id="formRangeYStand">
    <div class="range" id="range_y_stand">
        <input type="range" min="1" max="5" steps="1" value="1" id="range_y_stand_input" name="range_y_stand_input">
    </div>
    <ul class="range-labels" id="range_y_stand_label" style="text-align: left;">
        <li class="active selected"><span></span></li>
        <li style="text-align: center; margin-left: -20px;"><span>Learning</span></li>
        <li><span>Can do</span></li>
        <li style="margin-left: 0px;"><span>Can do well</span></li>
        <li style="margin-left: -4px; text-align: right;"><span>Mastered</span></li>
    </ul>
    <button type="submit" style="margin-top: 20px">Submit</button>
</form>

My Javascript code

Query("#formRangeYStand").submit(function () {
        event.preventDefault();
        var link = '/wp-admin/admin-ajax.php';
        var form = jQuery("#formRangeYStand").serialize();
        var formData = new FormData;
        formData.append('action', 'testiram');
        formData.append('testiram', form);

        jQuery.ajax({
            url: link,
            data: formData,
            contentType: false,
            processData: false,
            type: 'post',
            success: function (result) {
                alert(result);
            },
            error: function (error) {
                console.log(error);
            }
        });

        return false;
    });

My PHP Code (functions.php)

add_action('wp_ajax_testiram', 'testiram');
add_action('wp_ajax_nopriv_testiram', 'testiram');


function testiram() {
     echo true;
    wp_die();
}

Result:

picture result

I know this is a common question but I still don’t understand why my code still returns zero in success response and I tried almost everything. Thanks in advance.

2

Answers


  1. true is not a valid response so it’s returning basically empty.

    Try json_encode(['success'=>true]) and then it’s extendable.

    If you must return true, just have it echo 'true', note the quotes so it’s a string.

    Login or Signup to reply.
  2. You can use WP predefine functions.

    add_action('wp_ajax_testiram', 'testiram');
    add_action('wp_ajax_nopriv_testiram', 'testiram');
    function testiram() {
        wp_send_json_success();
    }
    

    Pass dataType : "json",

    jQuery.ajax({
        url: link,
        dataType : "json",
        data: formData,
        contentType: false,
        processData: false,
        type: 'post',
        success: function (result) {
            alert(result);
        },
        error: function (error) {
            console.log(error);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search