Reputation: 777
I have a problem where I need to only update a part of the web page when someone adds a label and not the whole page.
pug front end:
h2 Labels
each labelName in label
h4 #{(JSON.stringify(labelName)).substr(1).slice(41, -1).replace(/['"]+/g, '')}
h2 Add a label
form(action='/labeling/#{name}/add_label', method='post', id='insertLabel')
label(for='insertLabel ') Add label
input(type='text', value='', name='label', id='insertLabel')
button(type="submit") submit
clicking submit makes a post request which is handled in the middleware here
router.post('/labeling/:stream_name/add_label', function (req, res, next) {
overallTime = '00:00:15'
labelName = req.body.label
db_label.insertLabel(labelName, overallTime)
db_label.findLabels((err, labels) => {
if (err) {
return res.sendStatus(500)
}
res.redirect('/labeling/' + outputName)
})
insertLabel inserts labelName and overallTime into mongoDB and findLabel brings back what labels stored in the relevant collection, the result looks like this
[ { _id: 5a7201d8a6a06f1627ad75ba, label: 'moo: 00:00:16' },
{ _id: 5a7201e9a6a06f1627ad75bb, label: 'moo2: 00:00:26' } ]
but I am getting lost among all the information I am getting. In this situation, should I use Jquery/Ajax, just Ajax, Axios or vanilla Javascript?
Upvotes: 0
Views: 494
Reputation: 177860
jQuery would be useful.
This needs to end up in the head of the page or just before the end of the page.
NOTE: I have renamed your form. You must have unique IDs!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
$(function() {
$("#insertLabelForm").on("submit",function(e) {
e.preventDefault(); // stop submission
// sending all form data - you can also do { "label": $("#insertLabel").val();
// instead of $(this).serialize()
$.post(this.action,$(this).serialize(),function(data) {
$.each(data,function(label) { // loop over result
$("#someContainer").append(label._id+":"+label.label+"<br/>");
});
});
});
});
</script>
Upvotes: 4
Reputation: 1441
I assuming that you need to add newly created Label name in #Lables
div. So I use Jquery for this.
Instead of retrieve back the all Lables result from table you can just append newly created Label name in to div. ( this will happens if the Label is created successfully.)
You should append your result to #Lables
<form id="insertLabelForm" action="/labeling/#{name}/add_label" method="post" id="insertLabel">
<label for="insertLabel">Add label</label>
<input type="text" value="" name="label" id="insertLabel"/>
<button type="submit">submit</button>
</form>
<script>
$(document).ready(function () {
$('#insertLabelForm').on('submit',function (e) {
e.preventDefault();
var newLableName = $('#insertLabel').val();
$.ajax({
url:$('#insertLabelForm').attr('action'),
method:"post",
data:$('#insertLabelForm').serialize(),
success:function () {
$('#Lables').append('<h4>'+newLableName+'</h4>');
}
})
})
})
</script>
Upvotes: 0