javascript - Update the todo list without refreshing the page in express nodejs app -


i newbee express nodejs applications. want make todo list. how looks far. question when add todo, takes time show change since reloads page. how can see change in realtime without reloading page. in advance.

in tasks.jade

 h1= title    .list     .item.add-task       div.action         form(action='/tasks', method='post', id='12345')           input(type='hidden', value='true', name='all_done')           input(type='hidden', value=locals._csrf, name='_csrf')           input(type='submit', class='btn btn-success btn-xs', value='all done')       form(action='/tasks', method='post')         input(type='hidden', value=locals._csrf, name='_csrf')         div.name           input(type='text', name='name', placeholder='add new task')         div.delete           input.btn.btn-primary.btn-sm(type="submit", value='add')     if (tasks.length === 0)       | no tasks.     each task, index in tasks       .item         div.action           form(action='/tasks/#{task._id}', method='post')             input(type='hidden', value=task._id.tostring(), name='id')             input(type='hidden', value='true', name='completed')             input(type='hidden', value=locals._csrf, name='_csrf')             input(type='submit', class='btn btn-success btn-xs task-done', value='done')         div.num           span=index+1             |.          div.name           span.name=task.name + ' (created at: ' + moment(task.createtime).format("yyyy/mm/dd") + ')'           //- no support delete method in forms           //- http://amundsen.com/examples/put-delete-forms/           //- xhr request instead public/javascripts/main.js         div.delete           a(class='btn btn-danger btn-xs task-delete', data-task-id=task._id.tostring(), data-csrf=locals._csrf) delete 

in app.js

app.get('/', routes.index); app.get('/tasks', tasks.list); app.post('/tasks', tasks.markallcompleted) app.post('/tasks', tasks.add); app.post('/tasks/:task_id', tasks.markcompleted); app.delete('/tasks/:task_id', tasks.del); app.get('/tasks/completed', tasks.completed); 

in tasks.js

exports.add = function(req, res, next){   if (!req.body || !req.body.name) return next(new error('no data provided.'));   req.db.tasks.save({     name: req.body.name,     createtime: new date(),     completed: false   }, function(error, task){     if (error) return next(error);     if (!task) return next(new error('failed save.'));     console.info('added %s id=%s', task.name, task._id);     res.redirect('/tasks');   }) }; 

expressjs server-side framework. means serves views when browser makes requests them. in order prevent browser making full page refresh when interacting page need client-side framework.

i highly recommend taking @ angularjs, can daunting framework beginner. first learn jquery if haven't already. many other frameworks either build on top of jquery directly or mimic of patterns employed jquery. focus on jquery first , graduate higher-level framework angularjs or similar.

here example of hijacking form submit jquery:

<script type="text/javascript">   $('#myform').on('submit', function (event) {     event.preventdefault(); // stop form causing page refresh.     var data = {       username: $('#username').val(),       password: $('#password').val()     };     $.ajax({       url: 'http://localhost/my/url',       data: data,       method: 'post'     }).then(function (response) {       // stuff response, add page dynamically.       $('body').append(response);     }).catch(function (err) {       console.error(err);     });   }); </script> 

if put script tag @ bottom of page, before closing </body> tag, hijack form id myform , attach event handler submit event. when form submitted event handler fire first. first line of handler event.preventdefault() tells browser not perform default submit behavior , refresh page. after create data object store values of form fields interested in. in example use text input id "username" , password input id "password". notice how string pass $() looks lot css selector, that's idea :)

once have data want post server, make ajax request data , handle response, or catch errors if occur. ajax request happens without refreshing page :)

the reason script has @ bottom of page because elements need loaded before runs. jquery makes possible ensure entire document ready before running scripts.

$(document).on('ready', function (event) {   // code won't run until whole page ready. }); 

if place code in event handler can put script tag anywhere on page, in <head>. jquery offers shortcut event handler because it's used lot.

$(function (event) {   // sugar $(document).on('ready', function () { ... }); }); 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -