$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>jQuery Ajax PHP function call returning [object Object]|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jQuery Ajax PHP function call returning [object Object]

matteradmin9PV0评论

I want to reload page using with jQuery Ajax. I have the code below, however, it's not working and is returning error [object Object]

Is this just a simple syntax problem, or is my whole logic problematic? It is working perfectly without Javascript, but I'm thinking the UI is more intuitive with jQuery Ajax.

functions.php

//enqueue scripts
function my_theme_enqueue_scripts() {
     wp_enqueue_script('jquery-ui', '.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' );

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');

Page Template PHP:

<form id="form-pm" method="post" enctype="multipart/form-data" action="">
            <table>
                <tr>
                    <td><textarea name="projectMessage" rows=3 id="project-message"></textarea></td>
                </tr>
                <tr>
                    <td><input type="submit" name="send" value="send message"></td>
                </tr>
            </table>
        </form>

my.js

function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');

            if($.inArray(hash[0], vars)>-1)
            {
                vars[hash[0]]+=","+hash[1];
            }
            else
            {
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
        }
        return vars;
    }

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

        e.preventDefault();
        var pID = getUrlVars()["id"];
        $.ajax({
            url: "admin-ajax.ajax_url",
            type: "POST",
            data: {
                action: "load_projectmessages",
                projectid: pID
            },
            success: function(data) { },
            error: function(errorData) { alert(errorData); }
        });
        return false;
    });

I want to reload page using with jQuery Ajax. I have the code below, however, it's not working and is returning error [object Object]

Is this just a simple syntax problem, or is my whole logic problematic? It is working perfectly without Javascript, but I'm thinking the UI is more intuitive with jQuery Ajax.

functions.php

//enqueue scripts
function my_theme_enqueue_scripts() {
     wp_enqueue_script('jquery-ui', 'https://code.jquery/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' );

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');

Page Template PHP:

<form id="form-pm" method="post" enctype="multipart/form-data" action="">
            <table>
                <tr>
                    <td><textarea name="projectMessage" rows=3 id="project-message"></textarea></td>
                </tr>
                <tr>
                    <td><input type="submit" name="send" value="send message"></td>
                </tr>
            </table>
        </form>

my.js

function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');

            if($.inArray(hash[0], vars)>-1)
            {
                vars[hash[0]]+=","+hash[1];
            }
            else
            {
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
        }
        return vars;
    }

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

        e.preventDefault();
        var pID = getUrlVars()["id"];
        $.ajax({
            url: "admin-ajax.ajax_url",
            type: "POST",
            data: {
                action: "load_projectmessages",
                projectid: pID
            },
            success: function(data) { },
            error: function(errorData) { alert(errorData); }
        });
        return false;
    });
Share Improve this question asked Feb 20, 2019 at 5:18 RollorRollor 1291 gold badge4 silver badges10 bronze badges 1
  • 1 get_results returns a php object, var_dump the contents to see its structure. – Milo Commented Feb 20, 2019 at 5:28
Add a comment  | 

1 Answer 1

Reset to default 1

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/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.

Post a comment

comment list (0)

  1. No comments so far