0

Consider the following scenario.

I am passing errors from nodeJS after validating a form. The page then reloads and the errors are loaded onto the refreshed page. However, the form itself is actually located inside a modal. How can I open that modal when errors are passed in a function like res.render() on server side?

How do I trigger a function located on a client-side js file based on a locals variable from the server side?

Server Side Code is something like this :

router.post('/create', [
    check('company_name').not().isEmpty().withMessage('Company Name must not be empty'),
    check('contact_name').not().isEmpty().withMessage('Contact Name must not be empty'),
], (req, res, next) => {
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        req.flash( 'errors', errors.mapped() );
        res.redirect('/client');
    } else {
        console.log('No errors found');
        var newClient = new client({
            company_name : req.body.company_name ,
            contact_name : req.body.contact_name ,
        });

        newClient.save(function(err){
            if (err) throw err;
        });

        console.log("Client Created!");
        req.flash('success_msg', 'You have created a new client!');
        res.redirect('/client');
   }
});
Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
Mac Ahmed
  • 55
  • 10
  • Put a script in the page that runs when the page loads that detects error information in the page and puts up the modal if there is error information in the page. It's up to you how it detects the error information in the page. It could be the presence of certain DOM elements or it could be a script variable you set a value in when rendering the page with the error data in it. Or, only put the script in the page when there is error information. The server constructs the page so you can put whatever you want in it based on the state. – jfriend00 Feb 26 '18 at 06:52

1 Answers1

0

you can pass that variable as in url and then on your init function or so like : http://yourdomain.com/sompage.whatever?error=yes; On the client at the beginning check for that variable in url if verifies some checks then show the modal. You can use URL Query String and or URL Parameters for an example of knowing the differences : What is the difference between URL parameters and query strings?

nullqube
  • 2,959
  • 19
  • 18