jQuery Ajax PHP function call returning [object Object]

OK, so there are multiple problems with your code…

1. Incorrect localization of script

Here’s your function that enqueues and localizes the scripts:

function my_theme_enqueue_scripts() {
     wp_enqueue_script('jquery-ui', 'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js', array('jquery'), '1.12.1');
     wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0');
     wp_enqueue_script('myjs');
     wp_localize_script( 'ajax-script', 'admin-ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

So you localize script called ajax-script, but there is no such script registered. It should be:

wp_localize_script( 'myjs', 'admin-ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

2. Incorrect name of variable

In wp_localize_script the second parameter is a name for variable that will be created in JS. You put admin-ajax in there and that isn’t a correct name for variable.

Change it to:

wp_localize_script( 'myjs', 'MyJS_Data', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

3. Incorrect AJAX url in $.ajax call

In my.js file you have:

$("#form-pm").submit(function(e) {

    e.preventDefault();
    var pID = getUrlVars()["id"];
    $.ajax({
        url: "admin-ajax.ajax_url",
        type: "POST",
        data: {

So you pass a string "admin-ajax.ajax_url" string as URL and this isn’t a correct url address…

It should be:

url: MyJS_Data.ajax_url,

as you want to use variable, and not a string and we’ve changed name of that variable in 2…

4. Incorrect usage of AJAX callback function.

In your PHP code you have:

function load_projectmessages($projectid) {
     global $wpdb;
     $sql_displaymessages = $wpdb->prepare("some sql", $projectid );
     $projectmessages = $wpdb->get_results($sql_displaymessages);
     return $projectmessages;
     wp_die();
}
add_action('wp_ajax_load_projectmessages', 'load_projectmessages');

But… This function doesn’t print anything, so your AJAX request won’t get any result.

On the other hand you do 2 things:

 return $projectmessages;
 wp_die();

So your function will return (not print) $projectmessages. The next line won’t be called, because function ends its execution, when you return a value.

So it should be something like this:

function load_projectmessages($projectid) {
     global $wpdb;
     $sql_displaymessages = $wpdb->prepare("some sql", $projectid );
     $projectmessages = $wpdb->get_results($sql_displaymessages);
     echo json_encode( $projectmessages );
     wp_die();
}
add_action('wp_ajax_load_projectmessages', 'load_projectmessages');

This way your function will “return” $projectmessages encoded as JSON.