Refactoring express app to 1 page using Ajax and JQuery

jquery
nodejs

#1

Hi!

I have just completed a basic web dev bootcamp online and I’m creating a practice blog for experience. However, I want to refactor the comments section using Ajax and JQuery so that the page does not need to re-load. I started a course on this and tried to update with Ajax code but I cannot get it to work!
Here’s my original POST route:

router.post("/", middleware.isLoggedIn, function(req, res){
// lookup blog using id
Blog.findById(req.params.id, function(err, blog){
    if(err) {
        console.log(err);
        res.redirect("/blogs");
    } else {
        // create new comment
        Comment.create(req.body.comment, function(err, comment){
            if(err) {
                req.flash("error", "Something went wrong");
                console.log(err);
            } else {
                if(req.xhr){
                    res.json(comment);
                } else {
                }
                comment.author.id = req.user._id;
                comment.author.username = req.user.username;
                comment.author.image = req.user.image;
                comment.save();
                // connect new comment to campground
                blog.comments.push(comment);
                blog.save();
                // redirect to campground show page
                req.flash("success", "Successfully added comment");
                res.redirect("/blogs/" + blog._id);
            }
        });
    }
});
});`

This is the Ajax code I have written:

    $('#newComment').submit(function(e){
 e.preventDefault();
 var formData = $(this).serialize();
 $.post("/", formData, function(data){
 console.log(data);
 });
});

And this is the form I am trying to extract data from:

    <% if(currentUser){ %>
 <div class = "container form">
   <form action = "/blogs/<%= blog._id %>/comments" method = "POST" id="newComment">
    <div class="row">
        <div class="col-md-2">
            <img class="newComment-ico" src = "<%=currentUser.image%>">
        </div>
        <div class="col-md-10">
            <label for="comment">Add comment</label>
        </div>
    </div>
        <textarea class = "form-control" rows="4" placeholder = "Type comment here..." name =  "comment[text]"></textarea>
        <button class = "btn btn-lg btn-primary btn-block">Submit</button>
    </form>
 </div>
 <% } %>

When running this code I get the following error in my chrome log:

Failed to load resource: the server responded with a status of 404 (Not Found)

And it points to the following line in JQuery:

            // Do send the request (this may raise an exception)
            xhr.send( options.hasContent && options.data || null );
        } catch ( e ) {

Can someone help!!!


#2

I can’t tell what might be going on at first glance but I’d recommend using curl or Postman to test the API endpoint you’re making. In your case, it’s probably not an issue with the client-side/ajax code you’ve written so it would be good to test the API endpoint and get it figured out there :ok_hand:


#3

Thanks for the advice. To be honest, as I’m still learning, not really sure how to go about that. I don’t suppose if I shared my space you could have a quick look? I kind of feel if I can just get this to work I’ll understand it all more!!!


#4

Not so fast :slight_smile: You should be able to figure it out with a little bit of research and positive reenforcement: you can do it!

Have a look at this overview video about Postman. And here’s another Postman video that can help that’s part of a series about building a webapp with Express so it might be even closer to what you’re looking for. Good luck, you’ll do great and don’t give up!


#5

OK thanks. To be honest no idea where to start with this!! Been staring at this code for about 2 days and just no idea what’s wrong. Oh well.
Cheers