How to jQuery Ajax show new data from successful insert?

admin2025-06-02  2

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?

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?

Share Improve this question asked Feb 21, 2019 at 18:23 RollorRollor 1291 gold badge4 silver badges10 bronze badges 5
  • Is there a particular reason you chose to use the older WP Admin AJAX instead of an authenticated REST API endpoint? – Tom J Nowell Commented Feb 21, 2019 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 Commented Feb 21, 2019 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 Commented Feb 21, 2019 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 Commented Feb 21, 2019 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 Commented Feb 21, 2019 at 23:42
Add a comment  | 

2 Answers 2

Reset to default 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.

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748879438a314483.html

最新回复(0)