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

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


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