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

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

Can JQuery be used to detect text input in real-time in a textarea field?

Currently, I have a button for "post" that becomes active when text is typed into the text area. The issue arises when all text is deleted from the text area, as the button remains active in its coloured state despite being disabled using the following cod ...

Is Handlebars indicating that it requires missing assistance?

Attempting to manually render a handlebars template on the server side using Express. //require handlebars var hbs = require('hbs').create({ svg: require('handlebars-helper-svg'), switch: require('../helpers/switch.js'), ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

Crafting a template for mixing up images and quotes without any specific connection - here's how!

I came across some interesting templates that can generate random quotes and others that create random pictures. My goal is to develop a template that generates both a random quote and a random picture, similar to this example, without any relation betwee ...

Anticipate that the function will remain inactive when the screen width is less than 480 pixels

Implementing Functionality in Responsive Navigation <script> document.addEventListener('DOMContentLoaded', () => { let windowWidth = window.Width; let withinMobile = 480; let close = document.getElementById('close&ap ...

Experiencing difficulty retrieving form data within Google Apps Script

My attempt to send form data to google sheet via ajax is encountering an issue with the if else statement in the google script not functioning correctly. Here is the snippet of the google script: // original from: http://mashe.hawksey.info/2014/07/google- ...

Retrieving Progress Updates from a PHP Script Using XMLHttpRequest

I am currently using JavaScript to execute an XMLHttpRequest to a PHP script that returns data. My goal is to display a progress bar for the user instead of a spinning circle, indicating the progress of fetching and receiving the data. While I understand t ...

Managing Numerous Dropdown Menus: Techniques and Tips

I'm currently working with MUI to design a navigation menu that contains dropdowns within certain links. However, I've encountered an issue where clicking on any button opens the same dropdown menu. Below is my code snippet: function Header() { ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...

Avoid refreshing the page when clicking on an anchor tag in Vue.js

I have the code below in my Vue file. The problem I am encountering is that the page reloads whenever I click on the link. I have tried using event.preventDefault() but it did not solve the issue. Can someone please help me identify what I am doing wrong ...

"Switching from vertical to horizontal time line in @devexpress/dx-react-scheduler-material-ui: A step-by-step guide

Is there a way to switch the Time to a horizontal line using @devexpress/dx-react-scheduler-material-ui? <WeekView startDayHour={7} endDayHour={20} timeTableCellComponent={TimeTableCell} dayScaleCellComponent={DayScaleCell} /> Click ...

Issue with Vuetify carousel not resizing to fit the entire width and height

I am looking to create a carousel that spans the entire width and height of a viewport in my Vue.js 2 project using Vuetify. Below is the code I have so far: <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500, ...

Is it feasible to make an ajax request to fetch data and then send it to a PHP file via a post

Trying to send an ajax GET request to an external controller when a button on the form is clicked in order to use the returned data to dynamically generate "results" using PHP/HTML. The ajax code being used (using jQuery() instead of $() due to wordpress& ...

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

The issue with Jquery Lightbox/Modal doubling upon clicking

Having just started with jQuery, I've encountered an issue with my Gallery Lightbox/Modal. Whenever I click on a thumbnail, the modal reopens itself and I'm unsure where to set a reset. Any help would be greatly appreciated. jQuery(function($) { ...

Tips on setting dynamic headers in tabulator

Is there a way to dynamically set the header name passed from JSON? Additionally, how can I hide multiple columns in Tabulator instead of just one? I would also like to be able to show/hide multiple columns on button click. These questions pertain to a co ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

Utilize React to generate HTML content and send it as the email body through Node.js

I am currently working on a react application that consists of two main pages - AddStatus and ViewStatus. Both of these are implemented as react components. My current task involves sending out an email daily at a specific time, containing the details dis ...