Express.js - Posted data not rendering until refresh the page - node.js

I am send and fetch data from MySql Database with Express.js and Sequelize.js. All my code works correctly. My problem is, posted data not rendering on the Handlebars template until refresh the page. I also tried res.render method after SaveSettings method but don't worked. I want to render updated data after redirect.
Solved
You're missing return before settings.update(). Without it, the SaveSettings promise resolves before the update has completed - #Phil
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
return settings.update(values).catch((e) => console.log(e));
}
});
}
Routes
router.get("/admin", csrf, isAuth, controller.getGeneral);
router.post("/admin", isAuth, controller.postGeneral);
Controllers
exports.getGeneral = (req, res) => {
Models.General.findByPk(1).then((result) => {
return res.render("dashboard/index", {
title: "General Settings",
data: result,
});
});
};
exports.postGeneral = (req, res) => {
SaveSettings(Models.General, req.body)
.then(() => res.redirect("/admin"));
};
SaveSettings Method
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
settings.update(values).catch((e) => console.log(e));
}
});
}
Frontend
<form action="" method="post" class="table-responsive">
<input type="hidden" name="_csrf" value="{{csrfToken}}" />
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-success">Save</button>
</div>
<table class="table table-striped table-sm mt-3">
<thead>
<tr>
<th scope="col">Slot</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td class="align-middle">Name</td>
<td class="align-middle">
<input
name="name"
class="form-control"
type="text"
value="{{data.name}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Description</td>
<td class="align-middle">
<input
name="description"
class="form-control"
type="text"
value="{{data.description}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Email</td>
<td class="align-middle">
<input
name="email_address"
class="form-control"
type="email"
value="{{data.email_address}}"
/>
</td>
</tr>
</tbody>
</table>
</form>

Related

Nodejs Wait for all promises to resolve and then redirect

I am facing the problem in redirecting to index page. Instead page refreshes to same create page perhaps due to large size images are still copying but why page refreshing instead of images waiting copying to finish and then redirecting.
module.exports.create_customModel_post = async (req, res) => {
const {images} = req.files
let myPromise = []
if (images) {
const dir = `./public/${req.body.slug}`
fs.mkdirSync(dir, { recursive: true });
for (let i = 0; i < images.length; i++) {
const uploadTo = `${dir}/${images[i].name}`
myPromise.push(new Promise(function(resolve, reject) {
images[i].mv(uploadTo, (err) => {
if(err){
reject(err);
}else{
resolve(uploadTo);
}
});
}));
}
}
Promise.all(myPromise).then(function(values) {
console.log(values),
// THIS REDIRECT IS NOT WORKING
res.redirect('/admin/custom-models')
}).catch(function (reasons) {
console.log(reasons);
});
}
Response from server
POST /admin/create-custom-model - - ms - -
new model is created & saved
[
'./public/testing/attachment_48549925.svg',
'./public/testing/brand-name.png',
'./public/testing/design.svg',
'./public/testing/model-name.png',
'./public/testing/path9080.png',
]
GET /admin/create-custom-model 200 12.375 ms - -
here is form I am using. Removed extra
<main>
<section class="">
<div class="container">
<h1>Create Custom Model</h1>
<table class="">
<form enctype="multipart/form-data" method="post">
<tr>
<td></td>
<td>
<input type="file" name="images" multiple>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Cancel </td>
<td><button type="submit" >Save</button></td>
</tr>
</form>
</table>
</div>
</section>
</main>

how to delete row from database immediately in react js?

I am able to do axios.delete to remove an item from my database. But won’t be updated immediately unless I refresh the page or go to another page. here is the full component
function GestImages() {
//load Data from db
load data is working fine :
const [images, setImages]=useState([])
useEffect(()=>{
Axios.get("http://localhost:4000/produit/images")
.then(res=>{
setImages(res.data)
})
.catch(err=>{
console.log(err.message)
})
},[])
// delete Data from db
const deleteImage=(id,e)=>{
Axios.delete(`http://localhost:4000/produit/images/${id}`)
.then((res)=>{
setImages(prevImages => prevImages.filter(image => image.id !== id))
})
.catch(err=>{
console.log(err.message)
})
}
return (
<div className="container">
<div className="row row-a">
<div className="col-lg-12 col-md-12 d-flex justify-content-between" style={{backgroundColor:'#000000'}}>
<h1 className="justify-content-start" style={{color:'#FFFFFF'}}>Ajouter des images</h1>
<Link to='/gest-images/add-images' style={{marginTop:"1%"}} ><button className="btn btn-primary justify-content-end">Ajouter</button></Link>
</div>
<div className="col-lg-12 col-md-12 ">
<table className="table table-hover">
<thead>
<tr>
<th scope="col">Produit Name</th>
<th scope="col">Image</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{
images.map(images=>(
<tr key={images.id}>
<th>{images.produits.produitName}</th>
<td style={{width:"30%"}}><img src={"../../images/"+images.pathImage} style={{width:"20%"}} alt="produit img"/></td>
<td><button className="btn btn-danger" onClick={(e)=>deleteImage(images.id)}>Supprimer <FontAwesomeIcon icon={faTrashAlt} style={{color:"#FFFFFF"}}/> </button> </td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
</div>
)
}
export default GestImages

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST. when deleting first item

I'm a beginner in Laravel 7. I am trying to create a checkout form when purchasing items. The problem is whenever I try to delete the first item the 'The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.' shows up. However, I am able to delete the following items under it that I put into the checkout form.
This is my CheckoutController
public function destroy($id)
{
Temp_order::where('id',$id)->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}
And this is the code for the table
<tbody>
#forelse ($order as $item)
<tr>
<td id="item_code">{{ $item->item_code }}</td>
<td class="cart_product_img" id="image">
<img src="" alt="Unavailable" style="width: 70px; height:70px"></img>
</td>
<td id="item_name">
{{ $item->item_name }}
</td>
<td id="price">
₱ {{ number_format($item->price, 2) }}
</td>
<td class="qty" id="qty">
<div class="qty-btn d-flex">
<div class="quantity">
<input type="number" class="qty-text" id="qty" step="1" min="1" max="300" name="quantity" value="{{ $item->quantity }}">
</div>
</div>
</td>
<td id="subtotal">
₱ {{ number_format($item->subtotal, 2) }}
</td>
<td>
<form action="{{ route('checkout.destroy', $item->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Remove</button>
</form>
</td>
</tr>
#empty
<tr>
<td>
<p> NO ITEMS IN CART </p>
</td>
</tr>
#endforelse
</tbody>
And this is my route
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('ordering', 'OrderingController')->middleware('auth');
Route::resource('inventory', 'InventoryController')->middleware('auth');
Route::resource('checkout', 'CheckoutController')->middleware('auth');
Can you help me masters?
Try to update CheckoutController
public function destroy(Temp_order $item)
{
$item->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}

When editing item from table, it pulls/saves the wrong information

So, I am working on a CRUD application and I am trying to make it so that I can edit the project when I click edit. I can successfully get the project ID with the req.params.id and it is successfully printing the correct information into the console but when I go to send it to my front end it is still updating the information for the first entry in the collection. Below is the code that I used for this.
Backend:
router.get('/edit/(:id)', function (req, res, next) {
var o_id = new ObjectId(req.params.id).toString();
db.collection('projects').find({
"_id": ObjectId(o_id).toString
}).toArray(function (err, result) {
if (err) return console.log(err)
// if user not found
if (!result) {
req.flash('error', 'Project not found with id = ' + req.params.id)
res.redirect('/projects')
} else { // if user found
console.log(result);
// render to views/user/edit.ejs template file
res.render('edit.ejs', {
user: req.user,
title: 'Edit User',
//data: rows[0],
projID: result[0]._id,
projName: result[0].projectName,
projStat: result[0].status,
projEngineer: result[0].engineer,
projCost: result[0].finalCost
});
}
});
});
Frontend for listing the projects:
<tbody>
<form action="/edit/<%=projID%>" method="post" class="d-flex align-self-center mx-auto" style="width:500px;height:500px;padding:0px;margin:0px;background-color:rgb(255,255,255);">
<tr>
<td>
<input type="text" class="form-control" name="projName" value="<%=projName %>">
</td>
<td>
<input type="text" class="form-control" name="projStat" value="<%=projStat %>">
</td>
<td>
<input type="text" class="form-control" name="projEngineer" value="<%=projEngineer %>">
</td>
<td>
<input type="text" class="form-control" name="projCost" value="<%=projCost %>">
</td>
</tr>
<button class="btn btn-primary btn-block" type="submit" style="background-color:rgb(4,148,74);">Submit</button>
</form>
</tbody>
Front end for editing
<tbody>
<form action="/edit/<%=projID%>" method="post" class="d-flex align-self-center mx-auto" style="width:500px;height:500px;padding:0px;margin:0px;background-color:rgb(255,255,255);">
<tr>
<td>
<input type="text" class="form-control" name="projName" value="<%=projName %>">
</td>
<td>
<input type="text" class="form-control" name="projStat" value="<%=projStat %>">
</td>
<td>
<input type="text" class="form-control" name="projEngineer" value="<%=projEngineer %>">
</td>
<td>
<input type="text" class="form-control" name="projCost" value="<%=projCost %>">
</td>
</tr>
<button class="btn btn-primary btn-block" type="submit" style="background-color:rgb(4,148,74);">Submit</button>
</form>
</tbody>
So I figured out my issue, the way I was querying the db returned all of the objects, I just had to loop over it and find where the id matches up. Thanks to #andreiNikolaenko for pointing out to check that.

How to display specific data in ejs from mongoose?

I am new to NodeJS and MongoDB .I want to specific data from my database using mongoose . Those specific data are decided by a searchIndex and searchValue which is provided as a post request
The ejs page which provides the searchIndex and searchValue
<form action="/searchDetails" method="post">
<table>
<tr>
<td>
Select Search Category:
</td>
<td>
<select name="searchIndex">
<option>Name</option>
<option>Rollno</option>
<option>Branch</option>
<option>Hostel</option>
<option>RoomNo</option>
<option>ContactNo</option>
<option>Semester</option>
<option>FName</option>
<option>MName</option>
<option>Address</option>
</select>
</td>
</tr>
<tr>
<td>Enter the Search Value:</td>
<td><input type="text" name="searchValue"></td>
</tr>
<tr>
<td><input type="Submit" name="Search"></td>
</tr>
</table>
</form>
This is my mongoose schema
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
username: String,
password: String,
});
var studentSchema=new mongoose.Schema({
Name:String,
Rollno:String,
Branch:String,
Hostel:String,
RoomNo:String,
ContactNo:String,
Semester:String,
FName :String,
MName:String,
Address:String,
});
mongoose.model('Students3', studentSchema);
mongoose.model('User', userSchema);
this is my server.js
router.post('/searchDetails', function(req, res, next) {
var searchIndex=req.body.searchIndex;
var searchValue=req.body.searchValue;
students.find({searchIndex:searchValue},function(err,data){
if(err)
{
console.log(err);
}
else if(!data)
{
console.log('no data');
res.redirect('/homepage');
}
else
{
console.log(data);
output=data;
res.redirect('/editStudents')
router.get('/editStudents',function(req,res,next){
res.render('editStudents',{output});
});
}
});
});
this is my ejs where i display the value
<table border="1">
<tr>
<td>
<i>Name</i>
</td>
<td>
<i>Rollno</i>
</td>
<td>
<i>Branch</i>
</td>
<td>
<i>Hostel</i>
</td>
<td>
<i>RoomNo</i>
</td>
<td>
<i>ContactNo</i>
</td>
<td>
<i>Semester</i>
</td>
<td>
<i>Father's Name</i>
</td><td>
<i>Mother's Name</i>
</td><td>
<i>Address</i>
</td>
</tr>
<%
output.forEach(function(name)
{
%>
<tr>
<td><%=name.Name%></td>
<td><%=name.Rollno%></td>
<td><%=name.Branch%></td>
<td><%=name.Hostel%></td>
<td><%=name.RoomNo%></td>
<td><%=name.ContactNo%></td>
<td><%=name.Semester%></td>
<td><%=name.FName%></td>
<td><%=name.MName%></td>
<td><%=name.Address%></td>
</tr>
<%
})
%>
</table>
But the problem is it doesnot display any data.please help

Resources