MrG
MrG

Reputation: 33

Update MongoDB using JQuery and ExpressJS and AJAX

I have got a delete function working using type: 'DELETE' this way and I am now trying to make an UPDATE function although I don't know if I'm doing this correctly, the code so far is the following:

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('/');
    });
});

So I want to update in MongoDB using $set and set the event_name to whatever the user inputs in the prompt(). The error on the consolole is:

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

Upvotes: 1

Views: 2296

Answers (2)

sharkdawg
sharkdawg

Reputation: 984

As already pointed out by Kevin you need to change your action verb from UPDATE to PUT on both client and server side.

On the server side you need to access the users input which is sent via the ajax request. If you have installed bodyparser middleware this will be available to you through req.body.

Also you are redirecting twice.

//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');
    });
});

Upvotes: 1

Kevin
Kevin

Reputation: 1319

Please try to change your $.ajax({ type:'UPDATE' to $.ajax({ type:'PUT' and change app.post('/events/update/:id', function(req,res) to app.put('/events/update/:id', function(req,res)

Upvotes: 1

Related Questions