简体   繁体   中英

How to send data with ajax, without reloading page? (Nodejs)

I can't send my data and save it in database, without reloading. I Can't even understand, why my page reloading. I have no idea, how I can solve my problem...

Here is my form:

        <form action="/user/change" method="post">
           Name: <input type="text" id="name" name='profile_name' value="{{myName}}">
           Surname: <input type="text" id="surname" name="profile_surname" value="{{mySurname}}">
           Age: <input id="profile_age" name="age" type="text" value="{{myAge}}">
           <input type="hidden" name="_csrf" value='{{csrfToken}}'>
           <input type="submit" value="Send" id="send_profile">
        </form>

Here is my ajax script:

$('#send_profile').click(function() {
    $.ajax({
        global: false,
        type: 'POST',
        url: /user/change,
        dataType: 'html',
        data: {
            name: $("#profile_name").val(),
            surname: $("#profile_surname").val(),
            age: $("#profile_age").val()
        },
        success: function (result) {
            console.log(result);
        },
        error: function (request, status, error) {
            serviceError();
        }
    });
});

And my Node.js request handler:

router.post('/change', function (req, res) {
var name = req.body.name,
surname = req.body.surname,
age = req.body.age

User.findOneAndUpdate({_id: req.user._id}, {$set:{name: name, surname: surname, age: age}}, {new: true}, function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }
    console.log(req);
    console.log('req received');
    res.redirect('/user/'+req.user._id);
});
});

On submit By default your form data will send on action attribute of your form. if it is empty them it will send data on the same page. for preventing the default functionality of submit of any form we use e.preventDefault();

$('#send_profile').click(function() {
    e.preventDefault();
    $.ajax({
        global: false,
        type: 'POST',
        url: '/user/change', // missing quotes  
        dataType: 'html',
        data: {
            name: $("#profile_name").val(),
            surname: $("#profile_surname").val(),
            age: $("#profile_age").val()
        },
        success: function (result) {
            console.log(result);
        },
        error: function (request, status, error) {
            serviceError();
        }
    });
});

Your page is reloading because your are submitting it with input type=submit.

Replace that with a regular button and it should work.

Edit: you can remove the post from the form tag as well.

As noted above the issue stems from using a form and a submit button, one solution is to remove the form and submit and just pull the data from the onClick handler. I personally prefer to leave a working form, just in case a person has JS disabled (rare, but possible) the form will still submit with a reload.

This method requires you prevent default behavior for the click event, I've added a simple event.preventDefault() call before your jQuery AJAX handler. It will prevent the default behavior of the event (in this case submitting the form via post) allowing your handler to do that without reloading the page.

More info on the event object


$('#send_profile').click(function(event) {
    event.preventDefault();

    $.ajax({
        global: false,
        type: 'POST',
        url: /user/change,
        dataType: 'html',
        data: {
            name: $("#profile_name").val(),
            surname: $("#profile_surname").val(),
            age: $("#profile_age").val()
        },
        success: function (result) {
            console.log(result);
        },
        error: function (request, status, error) {
            serviceError();
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM