1

I'm currently trying to create a system where I can perform CRUD operations on a wordpress front end. I've seen a few plugins with shortcodes that allow this, so that is one possibility. However, ideally, I would like to use javascript (i.e. when a button is pressed somehow make some call to the SQL database and update a column in the table, etc.).

Is it possible to have dynamic javascript like this on a wordpress site?

Thank you.

1
  • 1
    Are you aware of the REST API and making HTTP requests in JS?
    – Tom J Nowell
    Commented Nov 30, 2020 at 10:57

1 Answer 1

1

Yes. You can do. Try using ajax, or better? using wordpress rest api

Ajax method: need register your function and action to do

Simple example:

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

function my_action() {
    return json_encode('hello word');
}
jQuery(document).ready(function() {
    var data = {
        'action': 'my_action'
    };
    jQuery.post(ajax_url, data, function(response) {
        alert(response);
    });
});

More info for ajax: https://codex.wordpress.org/AJAX_in_Plugins

Wordpress rest api: need to register a route

very simple example:

add_action( 'rest_api_init', function () {
  register_rest_route( 'yourName/v1', '/myroute', array(
    'methods' => 'POST',
    'callback' => 'my_function',
  ) );
} );

function my_function( $data ) {
  return 'Hello World';
}
jQuery(document).ready(function() {
    jQuery.post('/wp-json/yourName/v1/myroute', function(response) {
        alert(response);
    });
});

More info: https://developer.wordpress.org/rest-api/

3
  • This is the old way of doing things, you should update the answer to include mention of the REST API
    – Tom J Nowell
    Commented Nov 30, 2020 at 10:57
  • Yeah right. But Ajax is still widely used Commented Dec 1, 2020 at 14:58
  • both methods are intended for AJAX, I've amended the answer to have a jQuery example, and switch the REST API from GET to POST so that they match
    – Tom J Nowell
    Commented Dec 1, 2020 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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