Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

todo-list.js is not working #10

Open
Tapudp opened this issue Mar 13, 2018 · 21 comments
Open

todo-list.js is not working #10

Tapudp opened this issue Mar 13, 2018 · 21 comments

Comments

@Tapudp
Copy link

Tapudp commented Mar 13, 2018

I've followed till the video#34 properly and done as instructed, but whenever now I add a new item I can't see it in the app , also same with the deleting the item from todo list .

I think I forget to add/include the todo-list.js file in the .ejs(views), does it concern to that or not? Please guide

@sliekens
Copy link

I think I forget to add/include the todo-list.js file in the .ejs(views), does it concern to that or not? Please guide

Yep. The video doesn't mention it but you have to add the todo-list script to the ejs file.

<script src="/assets/todo-list.js"></script>

@Tapudp
Copy link
Author

Tapudp commented Mar 17, 2018

Oooh thanks!

elcymon added a commit to elcymon/node-js-playlist that referenced this issue Jun 16, 2018
@chaabninasser
Copy link

the delete not working!!!!

@chaabninasser
Copy link

the delete list don't work:;;;;!!!!

@LiviuSosu
Copy link

@chaabninasser It works, at least for the last 6 video tutorials. Can you please provide more details, or share the code snippet?

@chaabninasser
Copy link

app.js
{
var express = require('express');

var todoController = require('./controllers/todoController');

var app = express();

app.set('view engine','ejs');

app.use(express.static('./public'));

todoController(app);

app.listen(3009);
console.log(' You are listening to port 3009');
}
todo-list.js
{
$(document).ready(function(){

$('form').on('submit', function(){

  var item = $('form input');
  var todo = {item: item.val()};

  $.ajax({
    type: 'POST',
    url: '/todo',
    data: todo,
    success: function(data){
      //do something with the data via front-end framework
      location.reload();
    }
  });

  return false;

});

$('li').on('click', function(){
var item = $(this).text().replace(/ /g, '-');
$.ajax({
type: 'DELETE',
url: '/todo/' + item,
success: function(data){
console.log('delete item ');
//do something with the data via front-end framework
location.reload();
}
});
});

});

}
todoController.js
{
var bodyParser = require('body-parser');

var data =[{item:'get something'} , {item:'do something'} , {item:'kick something'}];

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports = function(app) {

app.get('/todo', function(req,res){
res.render('todo', {todos: data});

});

app.post('/todo', urlencodedParser , function(req, res){

data.push(req.body);
res.json(data);

});

app.delete('/todo/:item', function(req,res){
data=data.filter(function(todo){
return todo.item.replace(/ /g, '-') !==req.params.item;
});
res.json(data);

});
}

}

todo.ejs
{

<title>Todo List</title>
<link rel="stylesheet" href="/assets/styles.css" type="text/css">

My todo List

Add Item
    <% for(var i=0; i < todos.length; i++){ %>
  • <%= todos[i].item %>
  • <% } %>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script> <script src="/assets/todo-list.js"></script>

}

@chaabninasser
Copy link

chaabninasser commented Sep 14, 2018 via email

@LiviuSosu
Copy link

@chaabninasser Your delete controller from todoController.js seems incorrect. You are not deleting anything at all.

here is how it should look.

app.delete('/todo/:item', function (req, res) {
    //delete the requested item from mongodb
    Todo.find({item:req.params.item.replace(/\-/g, " ")}).remove(function(err,data){
        if(err){
            throw err;
        }
        res.json(data);
    });
});

Let me know if now it works.

@chaabninasser
Copy link

chaabninasser commented Sep 15, 2018 via email

@LiviuSosu
Copy link

LiviuSosu commented Sep 18, 2018

@chaabninasser Sorry for my late reply!
Did you just want to raise this issue? I am not sure if the api is not deleting from a dummy array or not.

Or you don't know how to enable removing the array from the delete controller? If you need help with this, please let me know and I'll see what I can do for you :-)

@khabib61
Copy link

I am having the same problem with the delete.
and my code is the exactly the same.

app.delete('/todo/:item', function (req, res) {
//delete the requested item from mongodb
Todo.find({ item: req.params.item.replace(/-/g, " ") }).remove(function (err, data) {
if (err) {
throw err;
}
res.json(data);
});
});

@begreat10
Copy link

Failed to look up view "todo" in views directory, please how do I solve this problem

@yonatantasew
Copy link

yonatantasew commented Apr 7, 2020

@khabib61 @chaabninasser

it is probably too late for a reply but here is how i solved it

by console.log() ing a lot of times i saw that the data we are getting from the click.event has to many spaces before and after the item
var item = $(this).text()
alert(item ) would show the spaces and var item = $(this).text().replace(/ /g, "-"); is making it worse since it is replacing all the spaces with "-" eg( -----------get-milk------- )
so what i did to solve this was
send the data to app.delete with all the spaces
todo-list.js
$('li').on('click', function() {

    var item = $(this).text()
    // alert(item)
    // var item = $(this).text().replace(/ /g, "-");
    // alert(item)
    
    $.ajax({
        type: 'DELETE',
        url: '/todo/ ' + item,
        success: function(data) {
            //do something with the data via front-end framework
            location.reload();
        }
    });
});

and on the to do controller i added a trim function

function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}

app.delete('/todo/:item', function(req, res) {

    function isFilter(d) {
        //console.log(" data = "+ d.item)
       // console.log("params ="+ req.params.item)
        var data2=myTrim(req.params.item)
        //console.log(d.item+data2)
      
       // return (d.item !== '  code  ')  
      
    return (d.item !== data2)
    
    }
    data=data.filter(isFilter)
    console.log(data);
    res.json(data);
});

that is it. enjoy .
i admit i could have made it a bit nicer with arrow functions but it works : -)

@napster007
Copy link

napster007 commented Jul 17, 2020

it turns out that
You just need to replace the values inside of the replace function if you are going to save it in MONGODB
Form:

Todo.find({item:req.params.item.replace(/ /g, '-')}).deleteOne((err,data)=>{
To:
Todo.find({item:req.params.item.replace(/^\s+|\s+$/gm,"")}).deleteOne((err,data)=>{

@AkshayAnand2002
Copy link

pls. point out error in my code for todo app by express. delete is not working. pls. tell where is the mistake.

todocontroller.js
//creation of routes and views for todo list can be done through controller so that work does get messy if we do everything in 1 file.
let data = [{ item: 'Feed the Dog' }, { item: 'Learn Node JS' }, { item: 'Go Shopping' }];
const bodyParser = require('body-parser'); //to access the data sent to us in the post request.
const urlencodedParser = bodyParser.urlencoded({ extended: false }); //middleware that we want to run in the postrequest.
module.exports = (app) => {
//now creating routes.i.e making handlers for different requests we are going to get. we will also need handlers for post requests.
app.get('/todo', (req, res) => {
res.render('todo', { todos: data });
//passing the 2nd parameter which is an object whcih gets passed to the view that we render it.
//above data passed into view with property name todo.
});
app.post('/todo', urlencodedParser, (req, res) => {
data.push(req.body); //for adding a new data we required to the array.
res.json(data); //send this data directly to front-end.
});
//to let users delete items from the list we need to handle a delete request.
app.delete('/todo/:item', (req, res) => {
data = data.filter((todo) => todo.item.replace(/ /g, "-") !== req.params.item);
//for deletion in this program use this line of code
//using a method called filter on data .
//we are firing functions and cycling through these objects and each one will be referenced as todo.
//The above statement returns true or false and if it is true then the item remains in the array.
//if false then the item comes out of the array.
res.json(data);
});
}; //calling modules which can be imported in app.js file.
//parameter app passed in function above.

todo.ejs

<title>ToDo List</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="/assets/todo-list.js"></script>
Add
    <% for(var i=0; i< todos.length ;i++) { %>
  • <%=todos[i].item %>
  • <% } %>

todo-list.ejs
//This is an already given file not written by me and this is going to handle our AJAX requests to add a post for deleted items
//in our ToDo application.
$(document).ready(function() {

$('form').on('submit', function() {

    var item = $('form input');
    var todo = { item: item.val() };

    $.ajax({
        type: 'POST',
        url: '/todo',
        data: todo,
        success: function(data) {
            location.reload();
        }
    });

    return false;

});

$('li').on('click', function() {
    var item = $(this).text().replace(/ /g, "-");
    $.ajax({
        type: 'DELETE',
        url: '/todo/' + item,
        success: function(data) {
            location.reload();
        }
    });
});

});

app.js
const express = require('express');
const app = express();
//above lines to setup express js.
//adding or making available controller operations in this file so that we get everything that is stored in this module.
const todocontroller = require('./controllers/todocontroller');
//now going to set ejs for template engine.
app.set('view engine', 'ejs');
//now we want to be able to serve static files so we use express middleware called express static.
// app.use('/assets', express.static('./public'));
//so from above in assets folder it is going to map to the static file .
//but the above code will make it path or route specific.
//to not to make it route-specific use -->
app.use(express.static('./public'));
//now add a port no. here app listens to port no. 3000
//controllers
todocontroller(app); //through this we return the functions from controllers.
app.listen(3000);
console.log('You are listening to port 3000.')

style.css
body {
background-color: aliceblue;
margin: 0 auto;
padding: 20px;
box-sizing: border-box;
}

input[type="text"] {
width: 300px;
padding: 16px;
font-size: 21px;
}

form {
text-align: center;
}

button {
padding: 16px;
background: green;
color: #fff;
cursor: pointer;
font-size: 21px;
}

ul {
list-style-type: none;
text-align: center;
}

li {
width: 100%;
padding: 21px;
box-sizing: border-box;
cursor: pointer;
}

li:hover {
text-decoration: line-through;
background: grey;
}

@walwyde
Copy link

walwyde commented Jun 15, 2022

Have you linked the ajax code (js script) to the html index page?
Import it as a script src'' ''.

@AkshayAnand2002
Copy link

Have you linked the ajax code (js script) to the html index page? Import it as a script src'' ''.

Hello,
I have not made index.html page . I simply made all the files linked them to app.js with todocontrollers then used nodemon for running the todo app.
Thanks for replying .
Pls. Tell error if you find .

@walwyde
Copy link

walwyde commented Jun 15, 2022

Try this in setting your static folder.
app.use(express.static('/public'))
Comment your code and try this.

@AkshayAnand2002
Copy link

I have already used this in my app.js file
you can see in line no. 13 in the app.js file.
Thanks.

@walwyde
Copy link

walwyde commented Jun 15, 2022

Okay.
I see a solution to your problem on this thread.
Please follow the comments carefully, check what @napster007 and @khabib61 posted.

@AkshayAnand2002
Copy link

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants