Home > OS >  wordpress ajax won't send response as array, why?
wordpress ajax won't send response as array, why?

Time:10-17

i have worked for wordpress project which need to call back some result from database via ajax .

the problem is the response will be in string form which is not as i aspect .

here is whats my try :

//The PHP
function edit_something() {
    
    if ( isset($_REQUEST) ) {
        global $wpdb;

         $ID = intval( $_REQUEST['ID'] );
             $query= "SELECT * FROM `TABLE` WHERE `ID` = '$ID';";
             $result= $wpdb->get_results( $queryHavadesEnsani, 'ARRAY_A' );
             print_r( $resultsHavadesEnsani );  
         }
    }


    die();
}
add_action( 'wp_ajax_edit_something', 'edit_something' );

and the endpoint

function myplugin_ajaxurl() {

echo '<script type="text/javascript">
       var ajaxurl = "' . admin_url('admin-ajax.php') . '";
       </script>';
}

add_action('wp_head', 'myplugin_ajaxurl');

at the end the jquery

function sendAjax( ID ) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    'action' : 'edit_something',
                    'ID' : ID
                },
                success:function(data) {
                    console.log(data)
                },
                error: function(errorThrown){
                    console.log(errorThrown);
                }
            });
        }

i realy need your guidance

more info :

i also tried json_encode for php and JSON.parse for js but error the response will be Object object .

CodePudding user response:

I guess instead of "echo" you should use wp_send_json_success

https://developer.wordpress.org/reference/functions/wp_send_json_success/

How to call ajax in Wordpress

  • Related