Whats the Workflow to save User Input from a Form


  • Hey guys,

    I'm currently testing around what I could do with a plugin. I've hooked up pages, put in some dummy data and it works flawlessly, I'm very impressed up to that point.

    But now I've been a bit stuck for 3 hours. I can't seem to find how to do one specific, usually simple thing:

    How do I save data a user put inside a form to the database?

    An example would be great here, I tried to catch the button press through the main.js file but I can't seem to figure out how to go on from that point on. Where should I get the request data (from the form) from, how is it going to be delivered, do I need to parse it to a nodejs function to actually access the database? And how would I go about all of that? Did I just miss another documentation? Because I'm pretty sure I've read every single page on docs.nodebb.org and couldn't find anything related to it despite the ability to create custom hooks but only in a nodejs context.

    Is there anyone here who can explain to me how this Workflow goes?

  • Gamers Admin

    It roughly goes like this.

    #1 Serialize the form data and send it to the server.

    submitBtn.on('click', function () {
      $.ajax(config.relative_path + '/myplugin/saveform', {
            data: $('#form').serializeObject(),
    	type: 'POST',
    	headers: {
    		'x-csrf-token': config.csrf_token,
    	},
    	success: function (data) {
         	    console.log('success');
    	},
            error: function(xhr, status, errorThrown) {
                console.log(arguments);
            }
      });
      return false;
    });
    

    #2 Create a post route in your plugin's static:app.load hook, and save the incoming data.

    const db = require('./src/database');
    plugin.init = async function(data) {
      data.router.post('/myplugin/saveform', [data.middleware.applyCSRF], async function (req, res) {
          await db.setObject('my-plugin-data', JSON.stringify(req.body)); // // req.body has the form data
          res.json('success');
      });
    };
    

    If your data is a flat object then you can save it without using JSON.stringify with just db.setObject('my-plugin-data', req.body);


  • @baris Thank you so much, gonna try it out as soon as I can 🙂


  • Okay mate thanks for the info, working fine now thanks a lot 😄

Suggested Topics

  • 11
  • 1
  • 1
  • 5
  • 3
| |