mr.loop
mr.loop

Reputation: 1005

Displaying Default value in HTML form from MySQL using node.js

I am having a scenario where I have to display a form and rather than taking input, I have to display some value extracted from database using nodejs. Below is the expected outcome

enter image description here

So, I wrote the following code

confirm.ejs

<form>
<label for="fname">First Name</label>
<input type="text" class="form-control" value="<%= ticket.Fname %>" id="fname" readonly>
</form>

js but I believe it is correct

router.get("/confirm",function(req,res){
    db.query("SELECT * FROM details WHERE Ticket=?",[variabled4],function(err, results, fields){
        if (err) throw err;
        res.render('confirm', { title: 'ticket info', ticket: results});
    });
});

So, I think the problem is in value = "<%= ticket.Fname %> and the whole form is displayed but with empty fields. (Fname is a column in details table with hello as value, not to be confused as a typo of fname)

Please suggest how to fix this.

Upvotes: 1

Views: 456

Answers (1)

Daniel
Daniel

Reputation: 2531

sequelize Raw Queries returns an array as response. You should check if the array is not empty and extract the ticket for results[0]

See: https://sequelize.org/master/manual/raw-queries.html

Here a small snippet (Handel the "ticket not found" as you see fit)

router.get("/confirm",function(req,res){
    db.query("SELECT * FROM details WHERE Ticket=?",[variabled4],function(err, results, fields){
        if (err) throw err;
         // on "results.length == 0" handle "ticket not found" flow

        let ticket = results[0];
        res.render('confirm', { title: 'ticket info', ticket: ticket});
    });
});

Upvotes: 1

Related Questions