ExpressJS routing don't match the content - javascript

I have a NodeJS app that displays some tables from a database. The view engine is ExpressJS.
On the app I have a dropdown list where u can select the table you want to display. The problem is that any given table that I want to display is only accessible through the dropdown, but what I'm trying to do is make them work through URLs.
So for example when u enter an address like: http://localhost:6789/tableOne, I want the table one to be displayed.
But if I load table two from the dropdown, and after that I enter the address I mentioned above, the page displays also table two, so basically is not refreshing with the new data. This makes the app working only through the interface, but I want to share to somebody else the direct link to a table and I can't. (they will receive the last table that was loaded on the app)
To rephrase, take as example an app that displays on the page the route's name. Mine doesn't update.
The routes are dynamically generated and here's an example of the routing that I did:
app.get('/someTables/:' + getNameFromID(selectedID), (req, res) => {
var url = req.url;
for (i in endData) {
if (i.name == url.substr(10)) {
selectedID = i.id;
}
}
res.render('index', { frontData2: endData2, frontData: endData, jsonToDisplayFrontEnd: jsonToDisplay, m1: m1, m21: m21, m22: m22, m1FrontEnd: m1ToDisplay, m21FrontEnd: m21ToDisplay, m22FrontEnd: m22ToDisplay, versionToDisplayFrontEnd: versionToDisplay, titleName: getNameFromID(selectedID), folderPath: getFolderPath(selectedID), folderPath2: getFolderPath2(selectedID) });
});
The function getNameFromID() returns a string.
How can I make this work? Thank you!

Related

Python Flask data feed from Pandas Dataframe, dynamically define with unique endpoint

Hi I am building a web app with Flask Python. I got a problem here:
#app.route('/analytics/signals/<ticker_url>')
def analytics_signals_com_page(ticker_url):
all_ticker = full_list
ticker_name = com_name
ticker = ticker_url.upper()
pricerec = sp500[ticker_url.upper()].tolist()
timerec = sp500[ticker_url.upper()].index.tolist()
return render_template('company.html', all_ticker=all_ticker, ticker_name=ticker_name, ticker=ticker, pricerec=pricerec, timerec=timerec)
Here I am defining company pages based on the a page will contain different content. The problem is that everything is fine upto ticker = ticker_url.upper(). It works perfectly fine. But for pricerec and timerec, they make problems.
sp500 is a pandas DataFrame columns being companies like "AAPL", "GOOG","MSFT", and so forth 505 companies and the index are timestamps, and values are the prices at each time.
So what I am doing for the pricerec, I am taking the ticker_url and use it to take the specific company's price and make it as a list. And timerec is to take the index (timestamps) and make it as a list. And I am passing these two variables into the company.html page.
But it makes internal server error. I do not know why it happens.
My expectation was that when a user click a button that href to "~/analytics/signals/aapl" then the company.html page will contain the pricerec and timerec for me to draw a graph. But it didn't work like that. It makes internal server error. I defined those two variables in the javascript also like I did for the other variables(all_ticker, ticker_name, and ticker)
Can anyone help me with this issue?
Thanks!

Mean.js Multiple Layouts, Server or Angular Layout

I've been developing a mean.js application. I have an admin theme that I'm trying to integrate with the existing application.
My question is
Can we have multiple Server Layouts, ? If the logged-in user is Regular User, use layout-1 if the user is Admin use layout-2
If we cannot have multiple server layout (I presume it isn't possible). Is there any way to detect the params or scope variable in the Angular Client App and dynamically load a partial inside the main Layout.
Let say I have an Index.html file, if the intended route is Dashboard, I just replace a section of the page view, ( Ruby on Rails Developers would know this)
UPDATE 1 :
I've created 2 files with my required Admin Index, and Layout files.
admin.index.server.view.html
and
admin.layout.server.view.html
I've also added the following code in my core.server.routes.js
module.exports = function(app) {
// Root routing
var core = require('../../app/controllers/core');
app.route('/').get(core.index);
app.route('/admin/').get(core.adminIndex);
};
I've also added the following code in my core.server.controller.js
exports.adminIndex = function(req, res) {
res.render('admin.index', {
user: req.user || null
});
};
and when I hit localhost:3000/admin/ I get Error: Cannot find module 'index'
Rename the two view files from admin.index.server.view.html and admin.layout.server.view.html to admin-index.server.view.html and admin-index.server.view.html respectively.
Also, change this line in your core.server.controller.js file;
res.render('admin.index', {
to this;
res.render('admin-index', {

How to load related entity of external data source in Lightswitch (Visual Studio 2013)

I have 2 tables which are both in an Azure SQL Database which is connected to my Lightswitch Sharepoint app. I am doing some manipulation of the data in code, and it appears to be working, except that when I load the entities from one table, I am not able to see the related entities in the other.
Basically, I have a products table and an invoice lines table. Each invoice line record contains a product code, which relates to the products table PK. I have defined the relationship in Lightswitch, but when I load the invoice line record, I can't see the product information.
My code is as follows:
// Select invoice and get products
myapp.AddEditServiceRecord.InvoicesByCustomer_ItemTap_execute = function (screen) {
screen.ServiceRecord.InvoiceNumber = screen.InvoicesByCustomer.selectedItem.INVO_NO;
// Delete existing lines (if any)
screen.ServiceDetails.data.forEach(function (line) {
line.deleteEntity();
});
// Add products for selected invoice
screen.getInvoiceLinesByNumber().then(function (invLines) {
invLines.data.forEach(function (invLine) {
invLine.getProduct().then(function (invProduct) {
var newLine = new myapp.ServiceDetail();
newLine.ServiceRecord = screen.ServiceRecord;
newLine.ProductCode = invLine.ProductCode;
newLine.ProductDescription = invProduct.Description;
newLine.CasesOrdered = invLine.Cases;
});
});
});
};
The idea is that a list of invoices are on the screen 'InvoicesByCustomer', and the user clicks one to add the details of that invoice to the 'ServiceRecord' table. If I comment out the newLine.ProductDescription = invProduct.Description line it works perfectly in adding the correct product codes and cases values. I have also tried a few other combinations of the below code, but in each case the related product entity appears as undefined in the Javascript debugger.
EDIT: I also read this article on including related data (http://blogs.msdn.com/b/bethmassi/archive/2012/05/29/lightswitch-tips-amp-tricks-on-query-performance.aspx) and noticed the section on 'Static Spans'. I checked and this was set to 'Auto (Excluded)' so I changed it to 'Included', but unfortunately this made no difference. I'm still getting the invProduct is undefined message. I also tried simply invLine.Product.Description but it gives the same error.
The solution in this case was a simple one. My data was wrong, and therefore Lightswitch was doing it's job correctly!
In my Invoices table, the product code was something like 'A123' whereas in my Products table, the product code was 'A123 ' (padded with spaces on the right). When doing SQL queries against the data, it was able to match the records but Lightswitch (correctly) saw the 2 fields as different and so could not relate them.
I may have wasted several hours on this, but it's not wasted when something has been learnt...or so I'll tell myself!

Fetch multiple collections with mongoose

Currently using node.js along with mongoose and express. I have two collections in my MongoDB and I can successfully retrieve data like this:
ActivityList.prototype = {
showActivities: function(req, res) {
point.find({}, function foundPoints(err, items) {
res.render('index2',{title: 'Credits' , points: items})
});
}
These data can be treated in my index.jade like this:
form(action="/asdad", method="post")
select(name = "item[point]")
each point in points
option(value='onlytesting') #{point.Activity}
input(type="submit", value="Update tasks")
As you can see I am using this to fill a drop down menu.. My issue is that i want to fill multiple drop down menus with data from other collections also.
The page is supposed to be my index.jade, such that a user is presented with multiple drop down menus which will be pulled directly from MongoDB.
My app.js calls:
app.get('/', activityList.showActivities.bind(activityList));
That works just fine, but I want to be able to fetch other data also with the "same" get..
Does anyone know how this can be accomplished?
Thanks for any tips

Django Dynamic Drop-down List from Database

I wanted to develop a Django app and one of the functionalities I'd like to have is dynamic drop-down lists...specifically for vehicle makes and models...selecting a specific make will update the models list with only the models that fall under that make....I know this is possible in javascript or jQuery (this would be my best choice if anyone has an answer) but I don't know how to go about it.
Also, I'd want the make, model, year and series to be common then the other attributes like color, transmission etc to be variables so that one needs only enter the make, model, year, and series only for a new vehicle. Any ideas would be highly appreciated.
The 3 things you mention being common, make, model, year, would be the 3 input values. When given to the server, an object containing the details would be returned to the calling page. That page would parse the object details (using JavaScript), and update the UI to display them to the user.
From the Django side, there needs to be the facilities to take the 3 inputs, and return the output. From the client-side, there needs to be the facilities to pass the 3 inputs to the server, and then appropriately parse the server's response.
There is a REST api framework for Django that makes it rather easy to add the "api" mentioned above -- Piston. Using Piston, you'd simply need to make a URL for that resource, and then add a handler to process it. (you'll still need to skim the Piston documentation, but this should give you an idea of what it looks like)
urls.py:
vehicle_details = Resource(handler=VehicleDetails)
url(r'^vehicle/(?<make>.*)/(?<model>.*)/(?<year\d{2,4}/(?P<emitter_format>[a-z]{1,4}), vehicle_details, name='vehicle_details'),
handler.py:
class VehicleDetails(BaseHandler):
methods_allowed = ('GET',)
model = Vehicles #whatever your Django vehicle model is
def read(self, request, *args, **kwargs):
# code to query the DB and select the options
# self.model.objects.filter()...
# Build a custom object or something to return
return custom_object
This simply sets up the url www.yoursite.com/vehicle/[make]/[model]/[year]/json to return a custom data object in JSON for jquery to parse.
On the client side, you could use jquery to setup an event (bind) so that when all 3 drop downs have a value selected, it will execute a $.get() to the api URL. When it gets this result back, it passes it into the Jquery JSON parser, and gives the custom object, as a javascript object. That object could then be used to populate more drop down menus.
(Big warning, I just wrote the following off the top of my head, so it's not meant to be copy and pasted. It's just for the general idea.)
<script type="text/javascript">
// On document load
$(function() {
$('#dropdown_make').bind('change', checkForValues());
$('#dropdown_model').bind('change', checkForValues());
$('#dropdown_year').bind('change', checkForValues());
});
function checkForValues() {
if ($('#dropdown_make').val() && $('#dropdown_model').val() && $('#dropdown_year').val())
updateOptions();
}
function updateOptions() {
url = '/vehicle/';
url += $('#dropdown_make').val() + '/';
url += $('#dropdown_model').val() + '/';
url += $('#dropdown_year').val() + '/';
url += 'json/';
$.get(url, function(){
// Custom data object will be returned here
})
}
</script>
This is uncanny: Dynamic Filtered Drop-Down Choice Fields With Django
His question:
"Here is the situation: I have a database with car makes and models. When a user selects a make, I want to update the models drop-down with only the models associated with that make. ... Therefore I want to use Ajax to populate the data."
You're not the same guy? :)

Categories

Resources