How to execute server-side code when clicking a button?

How can I do something like,
When I click on a custom button, I want to run some server side code.

For instance One button click I want to run file Jobs/Secheduled/test_job.rb

Or Can I run the code inside this file when somebody visits the url admin/plugins/my-plugin.

I am a beginner to discourse plugin development, And really struggling to do something like this, Any help will be much appricated

Then you’ll need to make an Ajax request to an endpoint that runs that code.

Can you say more about what you want to happen on the server side?

I want execute the code inside file Jobs/Secheduled/test_job.rb

Or you can say I want to run a cron job.

Can you please show me an example code how can I make ajax request to an endpoint and execute the code inside the file.

You’re still describing your solution and not the problem you’re solving. What do you want to do in that file? There may be a better way to trigger it. Knowing that will also make it easier to suggest something similar.

The subscription plugin adds an endpoint, so you might look at that. You’ll need to add a route in rails and then in ember add an action to your button that will call it.

I have a user with huge number of posts. I want to delete all posts of for that user the default delete all posts button giving 503 error. So I written a code schedule a cron job to run every 2 minutes and delete 100 posts at a time

Just run it at the rails console and don’t write a plugin.

2 Likes

Use the language features and do as @pfaffman suggests. Writing a bespoke front end hook to achieve this is seriously OTT.

See: ActiveRecord::Batches

I am not familiar to rails. Can you show me the command to delete posts for that user

1 Like

You can try searching for PostDestroyer

Yes, you are but there are many such users on the site. And my client is non-technical person how will he that.I need to write a plugin as the client institng me

And also the issue can arises in other forums website. We really need to have a look at the issue I am facing. we can make improvements in default delete post feature in future update

I have added button and onclick sended a ajax request to and end point I created but its resulting below error to my log file

Started POST "/delete-topic-ui/delete" for 122.173.29.28 at 2023-05-22 11:46:16 +0000

ActionController::RoutingError (uninitialized constant DeleteUserPostsController)

lib/middleware/omniauth_bypass_middleware.rb:74:in `call'

lib/content_security_policy/middleware.rb:12:in `call'

lib/middleware/anonymous_cache.rb:369:in `call'

config/initializers/100-quiet_logger.rb:20:in `call'

config/initializers/100-silence_logger.rb:29:in `call'

lib/middleware/enforce_hostname.rb:24:in `call'

lib/middleware/request_tracker.rb:228:in `call'

here is the url for my repo GitHub - rajsh011/delete-topic-ui: A sample plugin to show how to use handlebars templates on a custom admin route

How can I fix this, Or what is wrong in it everything is implemented as suggested by discourse and rails.

Any help will me much apricated, I am struggling with it from days

I am still stucked at this, What can be main cause of the issue below is my implementaion of code
===> plugin.rb

Discourse::Application.routes.append do
  get '/admin/plugins/delete-topic-ui' => 'admin/plugins#index'
  get '/admin/plugins/delete_all_posts' => 'delete_user_posts#delete_all_posts'
end 

===> app\controllers\delete_user_posts_controller.rb

 class DeleteUserPostsController < ApplicationController
  #  before_action :ensure_admin, only: [:delete_all_posts]
  
    def delete_all_posts
 #     username = params[:username]
       username = SiteSetting.delete_posts_for_username
      user = User.find_by_username_or_email(username)
  
      if user
        PostDestroyer.new(current_user).destroy_all_posts(user)
        redirect_to admin_index_path, notice: "All posts by #{username} have been deleted."
      else
        redirect_to admin_index_path, alert: "User not found."
      end
    end

    def ensure_admin
        unless current_user&.admin?
          render json: { error: 'Unauthorized' }, status: :unauthorized
        end
    end
end

===> assets\javascripts\discourse\controllers\admin-plugins-delete-topic-ui.js.es6

import { ajax } from 'discourse/lib/ajax';

export default Ember.Controller.extend({
  actions: {
    deletePosts() {
      ajax('/admin/plugins/delete_all_posts', {
        type: 'GET',
        data: {
          // Include any data you want to send to the server in the request body
          // Example: param1: 'value1', param2: 'value2'
        } 
      })
        .then(response => {
          // Handle the success response
          console.log(response);
        })
        .catch(error => {
          // Handle the error
          console.error(error);
        });
    },
    test() {
      ajax('/test', {
        type: 'GET',
        data: {
          // Include any data you want to send to the server in the request body
          // Example: param1: 'value1', param2: 'value2'
        },
        dataType: 'text'
      })
        .then(response => {
          // Handle the success response
          console.log(response);
        })
        .catch(error => {
          // Handle the error
          console.error(error);
        });
    },
    testjob() {
      ajax('/testjob', {
        type: 'GET',
        data: {
          // Include any data you want to send to the server in the request body
          // Example: param1: 'value1', param2: 'value2'
        }
      })
        .then(response => {
          // Handle the success response
          console.log(response);
        })
        .catch(error => {
          // Handle the error
          console.error(error);
        });
    }
  }
});

===> assets\javascripts\discourse\templates\admin\plugins-delete-topic-ui.hbs

 <h3>Delete User Posts</h3>
 
 <div class='buttons'>
  {{!-- {{d-button label="delete_topic_ui.delete" action="deletePosts" icon="eye" id='deletePosts'}} --}}
  {{d-button label="delete_topic_ui.delete" action=(action "deletePosts") icon="eye"}}
  {{d-button label="test" action=(action "test") icon="eye"}}
  {{d-button label="testjob" action=(action "testjob") icon="eye"}}
</div>