Home > Mobile >  Show last inputed value in ejs from sql
Show last inputed value in ejs from sql

Time:06-13

I want to Show last inputted value in Ejs from mySql, this in my code

js

router.get('/forming',showForm);
function showForm(req, res, next) { 
  console.log("test1");
  var getQuery = "SELECT tableone, mksa FROM myDataBase ORDER BY id DESC LIMIT 1";
  let query = db.query(getQuery, (err,result) => {
    if(err){
      console.log(err);
    }
    res.render('myejs_form_file',{ articleData: result });
    });
};
router.post('/create', function(req, res, next) {

  const userDetails=req.body;
  
  var sql = 'INSERT INTO myDataBase SET ?';
  db.query(sql, userDetails,function (err, data) { 
      if (err) throw err;
         console.log("Details is inserted successfully "); 
  });
 res.redirect('/article/forming');  // redirect to user form page after inserting the data
}); 

Ejs

<div >
          <h2>Input Content & MKSA</h2>
          <form action="/article/create" method="POST">
                <label>First Name</label>
                <input type="text" placeholder="Enter First Name" name="FirstName" required>
                <label>Last Name</label>
                <input type="text" placeholder="Enter Last Name" name="LastName" required>
                <button type="submit">Submit</button>
          </form>
          
      </div>
      <div>
        <table >
          <% articleData.forEach(data => { %>
              <p><%= data.FirstName %> this</p> 
              <p><%= data.LastName %> this</p>
              <% }) %>
      </table>
      </div> 

this code first input data from user, then when click submit it will store it's value on mySql Database, I want this to also showing again it's value, it's work but not showing the last just 2nd last, sorry my English is bad. all help is much appreciated

CodePudding user response:

Your redirection happens synchronously, possibly before the database insertion has finished. That's why the SELECT in GET /forming does not yet see the most recently inserted value.

Put the redirect statement into the callback function to have it executed asynchronously:

router.post('/create', function(req, res, next) {
  ...
  db.query(sql, userDetails, function (err, data) { 
    if (err) next(err);
    else {
      console.log("Details is inserted successfully "); 
      res.redirect('/article/forming');
    }
  }
});
  • Related