0

I'm trying to post data to a custom table via Ajax call and it works fine (rows are being inserted in MySQL custom table) but I'm not getting success response true in console.log.

Here is my code.

PHP

function create_link() {
    global $wpdb;

    if ( check_ajax_referer( 'create_link', 'nonce', false ) == false ) {
        wp_send_json_error();
    }

    $table_name = $wpdb->prefix . "custom_table";

    $result = $wpdb->insert( 
        $table_name, 
        array( 
            'icon' => sanitize_text_field($_POST['icon']), 
            'text' => sanitize_text_field($_POST['text']), 
        )
    );

    if ( $result == false ) {
        wp_send_json_success( 'Link has been created' );
    } else {
        wp_send_json_error();
    }

    wp_die();

}

add_action( 'wp_ajax_create_link', 'create_link' );

Javascript

( function( $ ) {

    $( document ).ready( function() {

        $( '.ufb-create' ).on( 'click', '.ufb-btn', function( event ) {

            var $button = $( this );

            $button.prop('disabled', true);

            var data = {
                'action' : 'create_link',
                'nonce'  : $button.data('nonce'),
                'icon' : $('.icon-input').val(),
                'text' : $('.text-input').val()
            };
        
            $.post(ajaxurl, data )
            .done( function (response) {

                console.log( response );

                if ( response.success == true ) {
                    // display success message
                    $('.ufb-create-response').html( response.data );

                } else {

                    // display error message
                    $( '.ufb-create-response' ).html("Something went wrong");
            
                }
                
                // enable button
                $button.prop('disabled', false);
            
            })
            .fail( function(error) {
                console.log(error)
            });
            
        
        } );        

    });

})( jQuery );

console.log(success)

{ "success": false }

Any help, please.

1
  • 1
    Try replacing ( $result == false ) with just ( $result )
    – Paul G.
    Sep 2, 2021 at 16:17

1 Answer 1

3

Look at your condition at the end:

if ( $result == false ) {
    wp_send_json_success( 'Link has been created' );
} else {
    wp_send_json_error();
}

wpdb::insert() returns false when there's an error, so you're only returning a success response when there's an error. You need to swap the statement around.

if ( $result == false ) {
    wp_send_json_error();
} else {
    wp_send_json_success( 'Link has been created' );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.