Reputation: 37
What would be the correct way to make the inventory update without refreshing the page and accessible through both the button event and url. So that when url param id is based to the route it will update it to the specific page. Like a products page on a shopping site. Below works through the ajax request but not through the url (inventory/2) it just takes me to the posted data and not with the rendered view. I require it to be able to go to a specific page by the url so I can link to it. It also needs to be able to fall back to just standard page loading when javascript is not enabled.
View (inventory)
extends layout
block content
div.row
div.col-md-offset-2.col-md-8#inventory
a(class='btn', href='#') Get More!
script.
$(function(){
$("a.btn").on("click", function(e) {
e.preventDefault();
$.get( '/inventory/2', function(data) {
$('#inventory').html(data);
});
});
});
Routes
router.get('/inventory/:id?', function (req, res) {
if(req.params.id){
var id = req.params.id;
var data = "Updated and now on page " + id
res.send(data);
}else{
res.render('inventory');
}
});
Upvotes: 1
Views: 1544
Reputation: 5395
Would recommend to have two separate sets of paths: one for the human users and one for the scripts (API). In your routes
file above, you mix the two - res.send(data)
is intended for the AJAX script, and res.render('inventory')
for direct display in the browser in response to the user's request - that is, basically, why you don't get the result you expected.
Please see a below a simple example how the app files can be structured (extend it as you see reasonable):
View:
extends layout
block content
div.row
div.col-md-offset-2.col-md-8#inventory
= content
a(class='btn', href='#') Get More!
script.
$(function(){
$("a.btn").on("click", function(e) {
e.preventDefault();
$.get( '/api/inventory/2', function(data) {
$('#inventory').html(data);
});
});
});
Routes:
var getData = function(id) {
return "Updated and now on page " + id;
}
router.get('/api/inventory/:id', function (req, res) {
res.send(getData(req.params.id);
}
router.get('/inventory/:id?', function (req, res) {
var data;
if (req.params.id) {
data = getData(req.params.id);
} else {
data = null;
}
res.render('inventory', {content: data});
});
(note: you may have to use != content
instead of = content
in the Jade template if your data
contains HTML.)
Now, the user can access different states of the page via urls /inventory
and /inventory/2
, while the AJAX call will be done using a third url, /api/inventory/2
.
On top of that, you can dynamically update the url field in the user's browser as may be needed - see the answers to this question for more details.
Upvotes: 1