Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far:

ejs:

<a href="#" class="editEvent" data-id="<%= event._id %>">Edit</a></p>

js:

$(document).ready(function(){
    $('.editEvent').on('click', editEvent);
});

function editEvent(){
    var change = prompt('Change to:', '');

        $.ajax({
            type:'UPDATE',
            url: '/events/update/'+$(this).data('id'),
            data: change
        }).done(function(response){
            window.location.replace('/');
            });
}

app.js:

app.post('/events/update/:id', function(req,res){
    db.events.update({_id: ObjectId(req.params.id)}, {$set: {event_name: data}},function(err, result){
        if(err){
            console.log(err);
        }
        res.redirect('/');
    });
});

I am looking to update in MongoDB using $set and assign the input from the user in the prompt() to the event_name. The error message appearing on the console is:

UPDATE http://localhost:3030/events/update/5a959fdb9effb926a0594d90 400 (Bad Request)

Answer №1

Kevin has already mentioned the need to switch the action verb from UPDATE to PUT on both the client and server sides.

To access the user's input sent via the ajax request on the server side, make sure you utilize the bodyparser middleware which will give you access to req.body.

Additionally, there seems to be a redundant redirection in your code.

//client.js    
$(document).ready(function(){
        $('.editEvent').on('click', editEvent);
    });

    function editEvent(){
        var change = prompt('Change to:', '');

            $.ajax({
                type:'PUT',
                url: '/events/update/'+$(this).data('id'),
                data: {event_name: change}
            }).done(function(response){
                console.log(response);
                window.location.replace('http://localhost:3030/');
            }).fail(function(response){
                console.log("Oops not working");
            });
    }

//app.js
app.put('/events/update/:id', function(req,res){
    const data = req.body; 
    db.events.update({_id: ObjectId(req.params.id)}, {$set: data},function(err, result){
        if(err){
            console.log(err);
        }
        res.send('updated successfully');
    });
});

Answer №2

It is recommended to update your code by changing $.ajax({ type:'UPDATE' to $.ajax({ type:'PUT' and also updating

app.post('/events/update/:id', function(req,res)
to
app.put('/events/update/:id', function(req,res)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

Error: The array's property is not defined

I am currently working on a visualization tool for sorting algorithms, but I keep encountering an error that says "Cannot read properties of undefined (reading 'map')" in line let bars = this.state.array.map((value, index) =>. You can find my ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Generating exportable dynamic code in Javascript

Any assistance or links to similar inquiries would be greatly welcomed as I have conducted some research but am uncertain about the best approach to take in this situation. I find it difficult to articulate exactly what I need, so I have created a visual ...

Search functionality in Laravel using Select2

I am currently facing an issue with the select2 jQuery plugin. I am unable to search for specific data that I need to display. Specifically, I am trying to search for a book name in my database within the branch of the company where I am located. This invo ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Errors in Data Capture from AJAX Dropdown Selections

Recently, I've encountered an issue with one of my data fields while attempting to save it to a mySQL database. The problem seems to be related to the fact that the 'id' for the text value is saved instead of the actual text value itself, wh ...

Generating a tree structure using a JavaScript array

Looking to build a tree structure from a given list of data where the paths are represented like: A-->B-->C-->D-->E.. A-->B-->C-->D-->F.. A-->F-->C-->D-->E.. . . . All possible data paths are stored in an array. The de ...

Click here to see the image

I'm looking to enhance an image with a hyperlink. This is the code I have so far. How can I make the image clickable? success: function(data, textStatus, jqXHR){ $.each( data, function( idx, obj ) { // $( "<img>" ).attr( "src", '/ima ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

What is the best way to compare two arrays of ids in MongoDB to find matching elements?

I have 2 arrays with different ids : bikesWithNoOrders [id , id1 , id2] filteredResult [id3 , id5] Is there a way to query and find all of them at once? This is what I currently have: queryBuilder.find({ _id: { $in: bikesWithNoOrders } }); queryBuilde ...

Keeping information saved locally until an internet connection is established

I have a vision to develop a Web app focused on receiving feedback, but the challenge lies in the fact that it will be utilized on a device without an internet connection. The plan is for it to save any user input offline until connectivity is restored. Th ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Is it possible to use reCAPTCHA without having to refresh the form page?

After successfully implementing the reCAPTCHA feature on my website following this tutorial: I encountered an issue with a complex JS form where the form data is lost when the user clicks the BACK button in the browser, unless it's written to a file. ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

Is there a way for me to showcase a collection of pictures in an array format

I am facing an issue on my react page where the data is successfully fetched from an API, but I am having trouble fetching the array of images. Below is the code snippet that I have written: import React, {Component} from 'react'; export defaul ...