0

I write messages into my db table with jQuery Ajax form post like this:

functions.php

add_action('wp_ajax_send_projectmessage', 'send_projectmessage');
function send_projectmessage() {
    global $wpdb;
    $wpdb->insert( //insert stuff to db table));

    wp_send_json_success();    
}

JS:

$('#form-pm').on('submit',function(e) {

        var mydata = { 
            'action': 'send_projectmessage',
            'projectid': projectid,  
            'message': message
        };

        var ajaxRequest =
        $.ajax({
            url: admin_ajax.ajax_url,
            type: 'post',
            data: mydata
        });

        ajaxRequest.done(function(data) { console.log(data); });
        ajaxRequest.fail(function(jqXHR) { alert(jqXHR); });

        e.preventDefault();
});

Everything works fine, data gets inserted into my database table.

Now, this is how I display the messages:

<div id="messages">
    <?php
    $messages = load_projectmessages($projectid);

    foreach ($messages as $message) {
    //make a <table><tr><td> with $message->themessage
    }
    ?>
</div>

<form id="form-pm>
    <!-- input fields and submit here -->
</form>

load_projectmessages is in the same functions.php:

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

My question is, where/when do I call load_projectmessages? Should I modify my whole JS ajax code to also do the displaying of new data?

  • Is there a particular reason you chose to use the older WP Admin AJAX instead of an authenticated REST API endpoint? – Tom J Nowell Feb 21 '19 at 19:22
  • @Tom, because I know nothing about how to do it using authenticated REST API endpoint. I had some experience with admin-ajax.php a few years ago, and I think it is still how it is done today – Rollor Feb 21 '19 at 20:43
  • A REST API endpoint is just a web address that returns JSON, but the API to use it is a lot easier, and does a lot of the heavy lifting for you, e.g. if you don't send the request right it'll tell you why it failed in plain english, whereas WP Admin AJAX just gives 0 – Tom J Nowell Feb 21 '19 at 21:30
  • Thank you @TomJNowell. I did notice the big /wp-json, so you're saying that with (REST API) I can focus more on writing and debugging my JavaScript, versus going through admin-ajax being a "hooker" (sorry for pun) in functions.php and keep refreshing my server error.log hoping to find clues as to why my ajax is returning 0 (or Bad Request 400) – Rollor Feb 21 '19 at 21:49
  • Yes, it lists the endpoints available to you at higher up endpoints, tells you if you gave the wrong parameters, etc, when you register your endpoint you can pass info about what it should expect, callbacks for validation etc, and it will handle it for you. The endpoint itself is just a function that takes a request object as an input, and returns an array/object as output, that gets turned into a JSON response with the appropriate HTTP code – Tom J Nowell Feb 21 '19 at 23:42
1

Modify your code as follows:

add_action('wp_ajax_send_projectmessage', 'send_projectmessage');
function send_projectmessage() {
    global $wpdb;
    $wpdb->insert( //insert stuff to db table));

    // Call your function to retrieve your data and send it to browser
    $messages = load_projectmessages($projectid);

    wp_send_json_success($messages);    
}

Display data through JS by modifying this

ajaxRequest.done(function(data) { console.log(data); });

to this

ajaxRequest.done(function(data) { 
    // Put markup for retrieved data here
    // for example 

    var o = "<table><tr><td>Project ID</td><td>Message</td></tr>";

    for (i=0; i<=data.length; i++){
        o .=  "<tr><td>"+data.projectid+"</td><td>"+data.message"+</td></tr>";
    }

    o .=   "</table>";

    $(#messages).html(o); 

 });

Also make sure that your function return an array instead of an OBJECT, so modify it as follows:

function load_projectmessages($projectid) {
    global $wpdb;
    $sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );

    // Add ARRAY_A to get result in an associative array
    $projectmessages = $wpdb->get_results($sql_displaymessages, ARRAY_A);
    return $projectmessages;

    // Not needed
    // wp_die();
}

I hope this will help.

| improve this answer | |
  • Thank you. This works, I'm just a bit stuck with , ARRAY_A, because the function is still returning an object – Rollor Feb 22 '19 at 0:40
  • I thought that wp_send_json_success() required an array parameter. But according to codex it can accept any type of parameter. So you can omit ARRAY_A thing in your code. – Qaisar Feroz Feb 22 '19 at 3:00
  • I just ended up using JSON.stringify(data.data[0].message_body). A little bit messy, but it works – Rollor Feb 22 '19 at 15:02
0

You can use wp_send_json_success to send messages back to the jQuery. The function accepts $data parameter that can basically be anything - plain text string, html, array.

So you could use your messages function inside your ajax insert function and have it send all the messages back to jQuery everytime. Or have the insert respond with only a (success) message related to that particular insert.

You could also add some kind of error handling to your insert function and have it do wp_send_json_error if something goes south during the insert.

| improve this answer | |

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.