0

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

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;
    });
  • 1
    get_results returns a php object, var_dump the contents to see its structure. – Milo Feb 20 at 5:28
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.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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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