Multiple delete in nodejs mysql using checkboxes - mysql

How do you perform multiple delete in nodeJs MySql? Where I need to check check-boxes to select the id's to be deleted in my blogger form.
front end
<% for(var i = 0 ; i < data.length ; i++) { %>
</td>
<td> <%= data[i].catname %> </td>
<td> <%= data[i].status %> </td>
<td> <%= data[i].id %> </td>
<td> delete</td>
<td> view</td>
<td> update</td>
<td> <input type="checkbox" name="check[]" value="data[i].id">delete <%=data[i].id %> </td>
<!-- making checkboxes -->
</tr>
back-end
app.post('/deletechecks',function(req,res){
var ch= req.body.check;
console.log(ch);
for(i=0;i<ch.length;i++)
{
var h= "delete from mydata where id='"+ch[i]+"''";
con.query(h,function(err,result){
if(submit==deleteselected)
{
console.log("deleted");
}
});
}
res.redirect('/viewdata');
});p.s i dont know what to do after this.

So hi there it's bit late while I am answering this .
So same situation I was there but the DB I was using was Mongo.
In my case it was a TO-DO list app where the user need to have a functionality of multipple delete so there were checkboxes were provided before the tasks.
I will attach a screenshot also for refernce.
While figuring it what I did I made a form there and first selected all task that I want to mark as done in case first and then hit delete so basically all will be deleted at once .
What happened I added a field 'name' in each task whose value I filled with the ObjectID in DB in order to make it unique OKAY! (As in the home page via EJS i had that info precomputed with me) (By EJS i mean View part or templating engine)
As once the Delete Button would be pressed (basically Submit) button then all these task values would be appended inside req.body (I think this you understad ) so what I did I casted the string values to ObjectID and called delete on the ID's .
So Now I am sending the pic and then code if still any issues in this do ask.
enter image description here The UI that I was talking above that will make things clear
And this is the delete function for reference :
Code:
app.post('/deleteTasks',function(req,resp){
let targetTask = req.body;
console.log('Hello there',targetTask);
let obj = [];
for(itr in targetTask){
const { ObjectId } = require('mongodb');
const _id = ObjectId(itr);
obj.push(_id);
}
console.log(obj);
for(itr of obj){
Task.findByIdAndDelete(itr,function(err){
if(err){
console.log('Error occured ',err.message);
return;
}
});
}
return resp.redirect('back');
});
Hope this can help and you can do some subsequent changes as per your quest .

Related

Strange behaviour while using 2 ngFor loops in Angular?

Below are two ngFor loops in HTML which are accessing elements when each of two seperate buttons are pressed.
<button (click)='payslips()'>Get Payslips</button>
<div>
<tr *ngFor="let payslip of objPayslips">----------->doesn't work, only works when 2nd button is pressed
<td>{{payslip.MonthYear}}</td>
</tr>
<h3>{{objPayslips | json}}</h3>-------->works fine
</div>
<button (click)='payslipdetails()'>Get Payslip Details</button>
<div>
<tr *ngFor="let index of objPayslipDetails;">
<td *ngIf="index.Addition">{{index.Addition}}</td>
<td *ngIf="index.AmountAddition">{{index.AmountAddition}}</td>
</tr>
<tr>
<td>Total Earnings: </td>
<td>{{payslipAdditionTotal}}</td>
</tr>
</div>
When Get Payslips is pressed then it's Object is generated and seen. But the same objects' values in the ngFor loop doesn't show up. But if I press the second button Get Payslip Details (which has a 2nd ngFor loop) then the values of 1st ngFor loop also show up. The two methods are completely different in the backend as well as the frontend. These methods are only run in a single HTML file. There is no link between these two methods anywhere. Then I don't know where is the problem. If I remove the 2nd button code entirely then the 1st code works fine which means that the ngFor loop shows values as it should. But both of them don't work properly alongside. Please have a look. Thankyou.
Edit:
Component.ts code:
payslipdetails(){
this.payrollService.getpayslipdetails(this.PId);
this.payslipEmployee=this.payrollService.objPayslipDetails[0];
this.objPayslipDetails=this.payrollService.objPayslipDetails;
//below code is to sum all the Earnings and Deductions. So to show their total values.
this.payslipAdditionTotal= this.payrollService.objPayslipDetails.filter((obj:any) => obj.AmountAddition).reduce((accumulator:any, obj:any) => {
return accumulator + obj.AmountAddition;
}, 0);
this.payslipDeductionTotal= this.payrollService.objPayslipDetails.filter((obj:any) => obj.AmountDeduction).reduce((accumulator:any, obj:any) => {
return accumulator + obj.AmountDeduction;
}, 0);
}
payslips(){
this.payrollService.getpayslips();
this.objPayslips=this.payrollService.objPayslips;
}
Service.ts code:
getpayslips(){
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer'+' '+GlobalService.authtoken);
return this.http.post<any>('http://localhost:3000/payroll/getpayslips/',null,{headers}).subscribe(({data}) => {this.objPayslips=data;})
}
getpayslipdetails(PId:number){
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer'+' '+GlobalService.authtoken);
return this.http.post<any>('http://localhost:3000/payroll/getpayslipdetails/',{"payslipId":PId},{headers}).subscribe(({data}) => {this.objPayslipDetails=data;})
}
This is an asychronous issue. You should grasp this concept before trying to use it.
In your service :
return this.http.post(...) // DO NOT put a .subscribe here
In your component TS file :
this.objPayslips = this.payrollService.getpayslips();
In your component HTML file :
<tr *ngFor="let payslip of objPayslips | async">

AngularJS push multiple rows from module

I have a form where the user choose a supplier from a select box, then a button to choose an item.
When he click the button, a module open and he can search for items. Result came into a table in the module, next to each row there is a + symbol, when he clicks the +, the row come outside the module, and place itself in the table in the main form.
<table>
<tr ng-repeat="row in searchitems">
<td>...</td>
<td>...</td>
<td> <a data-dismiss="modal" ng-click="additemfound(row)"></a> </td>
</tr>
</table>
javascript code:
$scope.additemfound = function(row){
$scope.rowrequest.push(row)};
here i get the row that i chose from the module to the main form and the module close.
I need to push from the module multi row, not only one by one, any solution ?
in the table :
<tr ng-repeat =" row in rowssearchitems"" ng-class="{'selected':
row.selected}" ng-click="addItemFound(row)">
in js
$scope.addItemFound = function(row) {
row.selected ? row.selected = false : row.selected = true;
in html again:
<button ng-click="getallrows();">Get all rows </button>
js:
$scope.getallrows = function(){
var selectedrows = $filter("filter")($scope.rowssearchitems, {
selected : true}, true);
for (var i=0;i<selectedrows.length;i++){
var selectedrowsdata = selectedrows[i];
$scope.rowsrequests.push(selectedrows[i])}
What I did :
I gave a class selected to every row where the user click on the row and the class become selected true then a loop on all rows selected true and push those rows to the main table

Express framework: How to capture a value on clicking an image and use that value to fetch database details into another html page

I have the following ejs file and I want to capture the NAME field value inorder to fetch the respective details from database and display onto another page. I know how to do this using form tag, but I am unsure how to capture in this case. Any help would be appreciated. Thanks.
search.ejs file:
<a href="/menu/<%= tablelist[i].NAME %>">
<img alt="<%= tablelist[i].NAME %>" class="restaurant-card-cover" src="<%= tablelist[i].IMAGELINK %>" style="height: 115px;">
<div class="restaurant-card-content-text">
<div id="catererName" class="restaurant-card-name heading-color" variable="<%= tablelist[i].NAME %>"><%= tablelist[i].NAME %></div>
<div class="card-description"><%= tablelist[i].DESC2 %></div></a>
In app.js file, I added the following:
app.get('/menu/:name', routes.menu(ibmdb,connString));
And, I have another folder "routes" and I am mentioning all my SQL queries in index.js file. Here it is:
exports.menu = function(ibmdb,connString) {
return function(req, res) {
var name = req.param.name;
ibmdb.open(connString, function(err, conn) {
if (err ) {
res.send("error occurred " + err.message);
}
else {
conn.query("SELECT ITEM_NAME, PRICE FROM HOMEBASEDAPP.MENU WHERE CATERER_NAME='"+name+"';", function(err, tables, moreResultSets) {
if ( !err ) {
res.render('menu', {"tablelist" : tables, name: name});
} else {
res.send("error occurred " + err.message);
}
/*
Close the connection to the database
param 1: The callback function to execute on completion of close function.
*/
conn.close(function(){
console.log("Connection Closed");
});
});
}
} );
}
}
I tried to print the "name" in menu.ejs file but its not getting the value.
This is done on the frontend.
One way to do that would be to add a data tag, say on the same div where you want to capture the click. I will take this div from you, but you can adapt:
<div class="restaurant-card-name heading-color"><%= table[i].NAME %></div>
Now, add a data tag, something we can put data in:
<div class="restaurant-card-name heading-color" data-restaurant="<%= table[i].NAME %>">
<%= table[i].NAME %>
</div>
Now, your div will render the name as a data attribute.
Then you have some click handler. Assuming jQuery here, you can grab a click on such divs. This bit javascript loaded when the dom is ready should do it:
$('.restaurant-card-name').click(function(evt) {
evt.preventDefault();
var name = this.data('restaurant');
$.ajax({
url: '/where/you/want/to/fetch/stuff/from',
method: 'POST',
// other stuff here, like displaying the data or image in a modal or similar.
})
});
Alternatively, if you want to just navigate to another page, as you say, there are a few steps.
First one is to prepare the url instead of the data attribute:
<a href="/my-restaurant-handler-route/<%= table[i].NAME %>">
<div class="restaurant-card-name heading-color">
<%= table[i].NAME %>
</div>
</a>
Now, your href value will be, for example, /my-restaurant-handler-route/mcdonalds
The second step is to prepare a route on the server. Since you're using ejs and you've tagged Node, I'll assume you're using express.
You need to prepare a route handler like this:
app.get('/my-restaurant-handler-route/:name', function(req, res) {
// param is on the request, whatever you named it after the `:` in app.get.
var name = req.param.name;
// now do the db dance
database.getData({restaurantName: name}).then(function(data) {
// you have the data, put it on the response or render it:
res.render('restaurant-handler.ejs', {data: data});
});
});
That is one way to do it. There are others, but you'll have to specify your situation a bit more for more details.

I wish to create a drop down select list with option items that can trigger http Get and refresh the page

I wish to create a drop down select list with option items that can trigger http Get and refresh the page.
I wish to run some code in the controller action when an option in the drop down is clicked.
I used the Html.DropdownlistFor() helper but I could not manipulate it thus.
Here is the code so you can understand me better,
var olist = db.ItemPackagingUnits.Where(i => i.ItemName.Equals(item.ItemName.ToUpper().Trim()));
<td>
<select>
#foreach(var oitem in olist)
{
<option value ='#oitem.UnitOfMeasurementName'>#oitem.UnitOfMeasurementName</option>
}
</select>
</td>
I hope I have given enough information on what I wish to achieve. DoSales is an action in the Restaurant Controller which has both Get and Post parts but I only wish to call the get part and refresh the page at the same time (or else I would have used Ajax or JSon) when the user clicks on any of the options in the drop down that was generated. Thank you.
Yes it worked! Thanks Mario J Vargas! Here are the code and javascript!
var olist = db.ItemPackagingUnits.Where(i => i.ItemName.Equals(item.ItemName.ToUpper().Trim()));
<td>
<select onchange ="myFunc(this)">
#foreach(var oitem in olist)
{
<option value ='/Restaurant/DoSales?ItemName=#item.ItemName&PackagingUnit=#oitem.UnitOfMeasurementName&recalulatePrice=true'>#oitem.UnitOfMeasurementName</option>
}
</select>
</td>
<script type="text/javascript">
function myFunc(myDropdown) {
//var myDropdown = document.getElementById(ddname);
window.location = myDropdown.options[myDropdown.selectedIndex].value;
}
Anon, your suggestion I believe has some merit and sounds feasible but I quickly implemented Mario's. Thanks for responding though. Indeed, there ain't no place like StackOverflow! Thanks again, Mario and Anon.

AngularJS, checkboxes, and generating dynamic html

I am wanting to generate a table dynamically using Angular JS, based on what is checked on some checkboxes. The problem is that there are a few fields, we will call them relation/column, that I want to display ALWAYS, and the remaining fields only if their box is checked. The relation is searched for via a search box (relations can have multiple columns), and I want to display only the properties of that relation that are relevant to a user.
So
Update Time [X]
Update Status [ ]
Time Zone [ ]
Would display some html along the lines of
<table>
<tr>
<th> Relation </th>
<th> Column </th>
<th> Update Time </th>
</tr>
<tr ng-repeat= "result in results">
<td> {{result.relation}} </td>
<td> {{result.column}} </td>
<td> {{result.update_time}}</td>
</tr>
If no boxes were checked, only the relation and column fields would be populated. The documentation for Angular JS is taking me all over the place, so would anyone have an idea on how to do this?
edit : controller isn't working quite yet, I still need to filter the search results, but basically it goes
$scope.search = function(){
//validate form input
//create url with the input recieved
$http.get(url).success(function(data){
$scope.results = angular.fromJson(data);
});
}
I use mojolicious backend to grab the data I want. Again, the problem isn't that I can't get any data, or that I can't filter the results based on the relation. I want to be able to search based on relation, and only display the attributes of that relation that I want to, based on what is checked. THAT part, I can't figure out.
edit again : the firewall where I'm at prevents me from writing comments/upvoting. You shall be rewarded for your help when I get home tonight. Thank you thank you!
I think the best way to do this would be using ng-show expressions tied to a variable in the model.
For example.
<input type="checkbox" ng-model="updateTime">
makes a checkbox and ties the result to $scope.updateTime. You can then use this variable later on via the ng-show directive like so...
<th ng-show="updateTime"> Update Time </th>
...
<td ng-show="updateTime"> {{result.update_time}}</td>
this means that these elements will only show when updateTime is set to true (i.e the checkbox is checked.)
You can see an example here, I've only implemented the one field but it should be possible to extend it pretty easily!
http://plnkr.co/edit/W6Ht6dnGw4fBplI83fB1?p=preview
I would suggest using a custom filter with the checkbox scope variables passed in. Something like this:
html
<input type="checkbox" ng-model="checkbox1" />
<input type="checkbox" ng-model="checkbox2" />
<input type="checkbox" ng-model="checkbox3" />
... ng-repeat= "result in results|checkboxFilter:{checkbox1,checkbox2,checkbox3}"
filter.js
.filter('checkboxFilter', function() {
return function (results, checkbox1, checkbox2, checkbox3) {
var filtered_objects = angular.copy(results);
for (var i = 0, len = filtered_objects.length; i < len; i++) {
**modify your filtered_objects based on your checkboxes**
if (checkbox1) ...
if (checkbox2) ...
if (checkbox3) ...
}
return filtered_objects;
}
});
Maybe something like that.