Get the data after redirect - mysql

I've a page '/order/new' that include 2 dropdown menues for customer & its address & a button that redirect to choose product to add to the order and I get the products in an array and pass the array to the '/order/new'..but when i redirect I don't get the selected customer & its address..I save the products which will be added in order in global array called hh which its get the data from ajax
I want to get the customer & its address after adding the product array
global.hh = new Array();
module.exports = {
getProduct: (req , res ) => {
var products = req.query.selectedProduct;
var total = req.query.sumTotal;
var btekh = hh.push(products)
}
getOrderProduct: (req , res) => {
let query1 = "SELECT * FROM `product`";
getConnection().query(query1 ,(err , result) => {
if(err) {
return res.status(500).send(err);
}
res.render('productOrder.ejs' , {
products: result
});
});
},
addOrderProduct: (req, res) => {
res.redirect('/order/new')
}
postOrder: (req ,res) => {
var products = req.session.products;
getConnection().query('INSERT INTO `order` ( clientId , addressId,orderStatusId) VALUES (?,?,?)', [req.body.selectUser, req.body.selectAddress,req.body.selectedStatus], (err,result) => {
if (err) {
console.log(err);
}
hh.slice(-1)[0].forEach(function (item) {
let insertedOrder = result.insertId;
let query = "INSERT INTO `orderProduct`( `orderIdProduct`, `productId`, `orderProductName`,`orderProductPrice`, `orderProductQuantity`, `orderProductTotal`) VALUES (?,?,?,?,?,?)";
getConnection().query( query , [insertedOrder,item.check,item.name,item.p,item.q,item.total] , (err , result)=>{
if (err) {
console.log(err);
}
res.end();
})
})
})
}
res.redirect('/')
}
app.get('/order/new' , addOrderPage)
app.use('/postOrder' , postOrder);
app.use('/order/product' , getProduct);
my ajax code:
////////////////add users's address///////////////////////////
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.addressId + "' > " + addressObj.addressName + " </option > ");
});
}
});
})
;
//////////////get the product to order/////////////
$('#save').click(function () {
var orderProduct = new Array();
$("#table input[type=checkbox]:checked").each(function () {
var row = $(this).closest("tr");
var message0 = row.find('#check').val();
var message1 = row.find('.name').text().trim();
var message3 = row.find('.currency').text().trim();
var message4 = row.find(".foo").val();
const result = {check: message0,name: message1,p: message3,q: message4 ,total: message3 * message4}
var hh = orderProduct.push(result);
});
console.log(orderProduct);
var totalPrice = 0;
orderProduct.forEach(function (item , index) {
totalPrice = totalPrice + item.total
})
$.ajax({
type: 'GET',
data: {selectedProduct: orderProduct , sumTotal: totalPrice},
url: '/order/product',
success: function (data) {
console.log(data);
}
})
})
My ejs for'/new/order':
<header>
<h2>New Order : </h2>
</header>
<form action="/postOrder" method="post" id="newForm" >
<label> User Name:</label>
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
<br>
<label>Product</label>
add product
<br>
<label>Status</label>
<select name="selectedStatus">
<% status.forEach((status) => { %>
<option value="<%= status.statusId %>"> <%= status.statusText %></option>
<% }) %>
</select>
<br>
<input type="submit" value="Save">
</form>

in these lines,
res.render('productOrder.ejs' , {
products: result
});
are you successfully getting all products from your DB back?
because in your AJAX call,
$.ajax({
type: 'GET',
data: {selectedProduct: orderProduct , sumTotal: totalPrice},
url: '/order/product',
success: function (data) {
console.log(data);
}
})
you're sending data, but not using it in your 'query1' here,
let query1 = "SELECT * FROM `product`";
I'm trying to get the flow of your program.
So the user goes to your webpage, they select a product, your webpage pings your REST server with the product information, your REST server pings your database looking for that product, then that data is rendered to this template here?
res.render('productOrder.ejs' , {
products: result
});
EDIT: You have to handle the user interaction with event listeners and the user input with some storage method.
Your_client-side_JS_script.js
function handle_submit(e) {
e.preventDefault();
if (e.target.id === 'addProduct') {
// When they click add product, you need to either pass their user details to the route and send them with the $.ajax GET request
//... and keep track of the data like that
// OR
// track that data in a cookie,
read up on cookies https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
} else if (e.target.id === 'newForm') {
console.log("Submit Form");
}
};
$('#addProduct').on('click', handle_submit);
$('#newForm').on('submit', handle_submit);
I recommend the cookie method. You set the cookie once, use it when you need it, then delete it when you're done.
With the first method, you have to send the data in your fetch (which doesn't need that data to get the products), then you have to manage that user_data throughout your back-end making sure it doesn't get lost. It's too much work. Use the cookie method instead.

Related

How to populate ejs form dropdown list options from MySQL database?

<div class="form-group">
<label for="Station_Type">Station Type</label>
<select name="Station_Type" class="form-control" name="Station_Type" id="Station_Type" autocomplete="off">
<option>Sewing</option>
<option>Cutting</option>
<option>Finishing</option>
<option>Distribution</option>
<option>Ironing</option>
<option>Offline</option>
</select>
</div>
I want the option values of this dropdown field to be populated by values stored in a separate table named 'stationoptions' in MySQL database which will be constantly updated. Right now, the options are hardcoded as shown in my code above, however, I want the dropdown list to be automatically updated whenever new values are added to the 'stationoptions' table in MySQL. May I know how do I query the data from MySQL to this form field?
This is how I insert the data from this form into another separate table. (in my .js file)
addPlayerPage: (req, res) => {
res.render('add-player.ejs', {
title: "Welcome | Add a new transaction",
message: ''
});
},
addPlayer: (req, res) => {
let playerId = req.params.id;
let LineNo = req.body.LineNo;
let Station_Type = req.body.Station_Type;
let query = "INSERT INTO `lineid` (id, LineNo, Station_Type) VALUES (NULL, '" + LineNo + "', '" + Station_Type + "')";
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
});
res.redirect('/line');
},
Try this:
<div class="form-group">
<label for="Station_Type">Station Type</label>
<select id="Station_Type" name="Station_Type" class="form-control" placeholder="Station_Type" value="<%= playerLine.Station_Type %>" required>
<!-- for loop code start -->
<% for(var i=0; i < playerLine.length; i++) { %>
<option value="<%= playerLine[i].Station_Type %>"><%= playerLine[i].Station_Type %></option>
<% } %>
<!-- for loop code end -->
<!-- and maybe you can remove this part -->
<option value="<%= playerLine.Station_Type %>"><%= playerLine.Station_Type %></option>
<option>Sewing</option>
<option>Cutting</option>
<option>Finishing</option>
<option>Distribution</option>
<option>Ironing</option>
<option>Offline</option>
<!-- and maybe you can remove this part -->
</select>
</div>
EDIT
In your js file:
addPlayerPage: (req, res) => {
// query the table you want show in your ejs
let myQuery = "SELECT field_name FROM table_name;" // query for the dropdown
db.query(myQuery , function(err, result) {
if (err) {
return res.status(500).send(err); // check if query have error
}
res.render('add-player.ejs', {
title: "Welcome | Add a new transaction",
message: '',
drecord: result // setting result reference for ejs
});
})
},
addPlayer: (req, res) => {
let playerId = req.params.id;
let LineNo = req.body.LineNo;
let Station_Type = req.body.Station_Type;
let query = "INSERT INTO `lineid` (id, LineNo, Station_Type) VALUES (NULL, '" + LineNo + "', '" + Station_Type + "')";
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
});
res.redirect('/line');
},
In you add-player.ejs:
<div class="form-group">
<label for="Station_Type">Station Type</label>
<select id="Station_Type" name="Station_Type" class="form-control" placeholder="Station_Type" required>
<!-- for loop code start -->
<% for(var i=0; i < drecord.length; i++) { %>
<option value="<%= drecord[i].field_name %>"><%= drecord[i].field_name %></option>
<% } %>
<!-- for loop code end -->
</select>
</div>

The value is not sent from dropdown to Express.js

I want to send the values of a form to Express.js to then save them in database. But the only value that is not reaching Express.js is the value in the select element. The form sends two things it sends an excel file and the value inside the select element. I even tried to console.log the req.body to see if the value is sent in the request body but it returns a void {} value. Here is the HTML.
<div class="w3-card-2 w3-display-middle" class="margin:auto">
<header class="w3-container w3-blue"><h4><b>Subir documento de Excel</b></h4></header>
<form id="uploadForm" enctype="multipart/form-data" action="/upload" method="post">
<br>
<input type="file" name="file" />
<br>
<br>
<label>Entidad financiera: </label>
<select name="bancos" class="w3-select w3-border"> /* <---------- */
<option value="noAsignado">No asignado</option>
<option value="bhdLeon">BHD Leon</option>
<option value="asociacionNacional">ASOCIACION NACIONAL DE AHORROS Y PRESTAMOS</option>
<option value="pucmm">PUCMM</option>
<option value="grupoAltus">GRUPO ALTUS</option>
</select>
<br>
<br>
<br>
<br>
<input class="w3-display-bottommiddle" type="submit" value="Subir" name="submit">
</form>
Here the Node code:
app.post('/upload', function(req, res){
console.log(req.body); // <---------------------
var exceltojson;
upload(req, res, function(err){
if (err) {
res.json({error_code:1,err_desc:err});
return;
}
if(!req.file){
res.json({error_code:1, err_desc:"No file passed"});
return;
}
if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson({
input: req.file.path,
output: "./outPutJSON/output.json",
lowerCaseHeaders: true
}, function(err, result){
if(err){
return res.json({error_code:1, err_desc:err, data: null});
}
res.json({datos:"Los datos fueron agregados exitosamente"});
fs.readFile("./outPutJSON/output.json", 'utf8', async (err, fileContents) => {
if (err) {
console.error(err);
return;
}
try {
let data = JSON.parse(fileContents);
console.log(data); //--------------HERE THE EXCEL FILE WHEN IS PARSED
io.emit('test event', 'Se han subido ' + data.length + ' casos' );
for(let cantidad = 0; cantidad < data.length; cantidad++){
var documento = data[cantidad];
if(documento.nombre === '' || documento.cedula === '' || documento.direccion === '') {
console.log('No se puede guardar este documento');
} else {
var mostrar = await incrementar();
documento.caso = mostrar;
documento.montoApoderado = data[cantidad]['monto apoderado'];
documento.numeroCliente = data[cantidad]['no.cliente'];
documento.numeroProducto = data[cantidad]['no.producto'];
let today = moment().format('YYYY M D');
documento.fechaCreado = today;
var mod = new model(documento);
await mod.save(documento);
}
}
} catch(err) {
console.error(err);
}
})
});
var fs = require('fs');
try {
fs.unlinkSync(req.file.path)
}catch(e){
}
} catch (e) {
res.json({error_code:1, err_desc:"Corrupted excel file"});
}
});
});
1-) Check that your express.js use the next sentences before calling the router methods:
app.use(bodyParser);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false })); // support encoded bodies
2-) You don't have an ID attribute attached to your tag and NAME attributes to select options (although the name is the one necessary for the server-side... :/)
You need to re-write your js code:
<select id="banks" name="bancos" class="w3-select w3-border"> /* <---------- */
<option name="noAsignado" value="noAsignado">No asignado</option>
<option name="bhdLeon" value="bhdLeon">BHD Leon</option>
<option name="asociacionNacional" value="asociacionNacional">ASOCIACION NACIONAL DE AHORROS Y PRESTAMOS</option>
<option name="pucmm" value="pucmm">PUCMM</option>
<option name="grupoAltus" value="grupoAltus">GRUPO ALTUS</option>
</select>
3-) Maybe you are checking the body before going through the next() function. Try before executing the handler and there, check the req.body again. :)
Best regards.

Unable to change the value of Filtered data length in angular4

I want to change the count of the filterdata [i.e. [(ngModel)]="filterdata"] after the data has arrived in the tables. For Example:
Initially in the text-box, i entered "experia" so all the data from the database that has experia appeared in the table. And the number of data is displayed on the right-hand of the table as you can see in the picture => "Number of searched data = 6". However, the issue is, if i enter text again in the search-text box and the data filters, but this filtered data number is not displayed, like "Number of searched data =4", of course this number will be less than the maximum number i.e.=6.It remains the same as >> "Number of searched data = 6" even though the total data displayed number is 4.
I have used an (ngModelChange) because i thought it might work, but it doesn't.
code:
transaction.component.html
<input class="form-control" id="input1-group1" style="margin-
top:20px" type="text" name="search" placeholder="Enter Search Text"
[(ngModel)]="filterdata" (ngModelChange)=
"countFilter(filterdata)"(keyup.enter)="searchByText(filterdata)">
//code
<h2> Transaction </h2>
<label *ngIf="toShowCount" id="arrayCountId"> Number of searched
data : {{arrayCount}}</label>
transaction.component.ts
countFilter(filtData){
console.log("inside countFilter = "+ filtData)
this.countFilterData = filtData.length;
if(this.arrayCount>=0){
if(this.countFilterData<this.arrayCount){
var result = [];
var url = config.url;
var port = config.port;
this.http.post("http://" + url + ":" + port +
"/transaction/masterSearchTransactionForm/", this.filterObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(result => this.result = result.json())
.subscribe((res: Response) => {
console.log("# DATE FILTER RESULT TRANSACTION XXXXXXXXXXXX",
res);
this.records = res;
this.toShowCount =true;
console.log ("the result of SearchByText is = ", this.result)
this.arrayCount = this.result.length;
console.log("ArrayCount = " , this.arrayCount)
console.log("search-by-text records = ",res)
console.log("Search by Text result is : " + result)
if (this.result.length > 0) {
this.notify.Success("Data Displayed Successfully");
this.loading = false;
}
else {
this.notify.Error("No Matching Data Available")
this.loading = false;
}
});
}
}
You don't need (ngModelChange)="countFilter(filterdata)" because as i can see you have 2 methods that call REST endpoint for filtering data: one in countFilter(filterdata) and the other one in searchByText(filterdata). When you call searchByText(filterdata) i presume that you are trying to filter data on server and get results. When you get that result from server, than you put length of that result in variable like you did in countFilter method.
this.arrayCount = this.result.length;
just put this in searchByText method and remove countFilter because you do not need it.
EDIT:
<input class="form-control" id="input1-group1" style="margin-
top:20px" type="text" name="search" placeholder="Enter Search Text"
#searchControl (keyup.enter)="searchByText(searchControl.value)"
(input)="countFilter($event.target.value)"
>
in your .ts file you will have a method searchByText(value) that calls API endpoint and query data table, something like this:
searchByText(value) {
this.http.post("http://" + url + ":" + port +
"/transaction/masterSearchTransactionForm/", this.filterObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(result => this.result = result.json())
.subscribe((res: Response) => {
this.records = res;
}
Now , you have saved all data that you queried first time with ENTER click
After this you want to have method that can filter through this saved data:
countFilter(value) {
this.records = this.records.filter((record) => record.name == value);
}
now you have a same variable (this.records) with filtered data! And in html you can just do string interpolation {{this.records.length}}

$.getJSON (url) not moving to the controller

I am developing my application in my MVC. I am using cascading dropdown list in my application. On selecting one i have 2 dropdown one is location and another one is employee. While selecting a location particular employee should be fetched in employee dropdown. I am using json result to retrieve the employee.
My code is
View Page
#Html.DropDownList("location", ViewBag.Location as SelectList, "Select the Location", new { id = "location" })
<div id=" employeediv" style="width:600px; height:50px">
<div style="float:left">
<label> Employee:</label>
</div>
<div style="margin-left:220px">
<select id="Employee" name="employee" style="width:150px"></select>
</div>
</div>
Script:
#section scripts{
<script type="text/javascript">
$('#location').change(function () {
#*var url = '#Url.Action("Employe", "Appt")';*#
//var url = "/Appt/Employee/"
debugger;
$.getJSON('/Appt/Employee/' + $('#location').val(), function (data) {
var item = '<option> Any </option>';
$.each(data, function (i, employee) {
item += "<option value ='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#employee").html(items);
});
});
</script>
}
Controller Code
public ActionResult CalendarView(int? id, int? CustomerUserid)
{
tblBusinessCategory bc = new tblBusinessCategory();
ViewBag.Location = new SelectList(from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc.LocationName);
return View();
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
My problem is While changing the location url is not redirecting to the controller and it is came out from its scope
$.getJSON('/Appt/Employee/' + $('#location').val(), function
Can anyone help me to solve this?
Thanks.

I cannot get my jqGrid to populate

Edited with working code as per Mark's answer below.
I'm really starting to loath MVC. I have been trying all day to get a simple grid to work, but I'm having more luck banging a hole in my desk with my head.
I'm trying to implement a search page that displays the results in a grid. There are 3 drop-down lists that the user can use to select search criteria. They must select at least one.
After they have searched, the user will be able to select which records they want to export. So I will need to include checkboxes in the resulting grid. That's a future headache.
Using JqGrid and Search form - ASP.NET MVC as a reference I have been able to get the grid to appear on the page (a major achievement). But I can't get the data to populate.
BTW, jqGrid 4.4.4 - jQuery Grid
here is my view:
#model Models.ExportDatex
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (e) {
var selectedSchool = $('#ddlSchool').children('option').filter(':selected').text();
var selectedStudent = $('#ddlStudent').children('option').filter(':selected').text();
var selectedYear = $('#ddlYear').children('option').filter(':selected').text();
var selectedOption = $('#exportOption_1').is(':checked');
if (selectedSchool == '' && selectedStudent == '' && selectedYear == '') {
alert('Please specify your export criteria.');
return false;
}
selectedSchool = (selectedSchool == '') ? ' ' : selectedSchool;
selectedStudent = (selectedStudent == '') ? ' ' : selectedStudent;
selectedYear = (selectedYear == '') ? ' ' : selectedYear;
var extraQueryParameters = {
school: selectedSchool,
student: selectedStudent,
year: selectedYear,
option: selectedOption
};
$('#searchResults').jqGrid({
datatype: 'json',
viewrecords: true,
url: '#Url.Action("GridData")?' + $.param(extraQueryParameters),
pager: '#searchResultPager',
colNames: ['SchoolID', 'Student Name', 'Student ID', 'Apprenticeship', 'Result'],
colModel: [
{ name: 'SchoolID' },
{ name: 'Student Name' },
{ name: 'StudentID' },
{ name: 'Apprenticeship' },
{ name: 'Result' }]
}).trigger('reloadGrid', [{ page: 1 }]);
});
});
</script>
#using (Html.BeginForm("Index", "Datex", FormMethod.Post))
{
<h2>Export to Datex</h2>
<div class="exportOption">
<span>
#Html.RadioButtonFor(model => model.ExportOption, "true", new { id = "exportOption_1" })
<label for="exportOption_1">VET Results</label>
</span>
<span>
#Html.RadioButtonFor(model => model.ExportOption, "false", new { id = "exportOption_0" })
<label for="exportOption_0">VET Qualifications</label>
</span>
</div>
<div class="exportSelectionCriteria">
<p>Please specify the criteria you want to export data for:</p>
<table>
<tr>
<td>School:</td>
<td>#Html.DropDownListFor(model => model.SchoolID, Model.Schools, new { id = "ddlSchool" })</td>
</tr>
<tr>
<td>Student: </td>
<td>#Html.DropDownListFor(model => model.StudentID, Model.Students, new { id = "ddlStudent" })</td>
</tr>
<tr>
<td>Year Completed:
</td>
<td>
#Html.DropDownListFor(model => model.YearCompleted, Model.Years, new { id = "ddlYear" })
</td>
</tr>
</table>
<table id="searchResults"></table>
<div id="searchResultPager"></div>
</div>
<div class="exportSearch">
<input type="button" value="Search" id="btnSearch" />
<input type="submit" value="Export" id="btnExport" />
</div>
}
Here is my Controller. As we don't have a database yet, I am just hardcoding some results while using an existing table from a different DB to provide record IDs.
[HttpGet]
public JsonResult GridData(string sidx, string sord, int? page, int? rows, string school, string student, string year, string option)
{
using (SMIDbContainer db = new SMIDbContainer())
{
var ds = (from sch in db.SCHOOLs
where sch.Active.HasValue
&& !sch.Active.Value
&& sch.LEVEL_9_ORGANISATION_ID > 0
select sch).ToList();
var jsonData = new
{
total = 1,
page = 1,
records = ds.Count.ToString(),
rows = (
from tempItem in ds
select new
{
cell = new string[]{
tempItem.LEVEL_9_ORGANISATION_ID.ToString(),
tempItem.SCHOOL_PRINCIPAL,
"40161",
"No",
"Passed (20)"
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
Is the JSON you are passing back to the grid valid? Are you passing back the information that the jqGrid needs? Why setup your jqGrid inside of an ajax call instead of inside your $(document).ready(function () { ?
Here is an example of the portion of code I use to format my json for jqGrid:
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from tempItem in pagedQuery
select new
{
cell = new string[] {
tempItem.value1,
tempItem.value2, ........
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
If you want to make your user search first, you can on the client side, set the jqgrid datatype: local and leave out the url. Then after your user does whatever you want them to do you can have the jqGrid go out and fetch the data, via something like:
$('#gridName').jqGrid('setGridParam', { datatype: 'json', url: '/Controller/getGridDataAction' }).trigger('reloadGrid', [{ page: 1}]);
If you want to pass in the search data, or other values to the controller/action that is providing the data to the jqGrid you can pass it via the postData: option in the jqGrid. To set that before going out you can set it via the setGridParam option as shown above via postData: { keyName: pairData}.
MVC and jqGrid work great...there are a ton of examples on stackoverflow and Oleg's answers are a vast resource on exactly what you are trying to do. No hole in desk via head banging required!