Functionality:
The functionality of this code is to update user details on the user Profile-page.
Code:
Profile.ejs
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
//alert(json);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}, false);
});
})();
</script>
<div id="res">
<h4>
<%= status %>
</h4>
</div>
<form id="test" action="/profile" method="post">
<input type="text" name="name" id="name" value=""/>
<input type="text" name="about" id="about" value=""/>
<input type="text" name="hobbies" id="hobbies" value=""/>
<input type="submit" value="send" class="btn btn-primary btn-block"/>
</form>
Index.js
router.get('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:''});
});
router.post('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:'Changes Updated'});
});
Expected-Outcome:
Once the post request with all the details are sent, the <div id="res"> should contain the text Changes Updated.
Actual-Outcome:
Once the post request is sent, 200 OK response is observed and the response packet has the text Changes Updated. However, the browser does not reflect it. The new response received is not rendered.
Kindly assist in resolving this issue, as I'm fairly new to this( And the entire code is put together from a lot of places ). Also, any extra information, or good reads on the subject would be much appreciated
$.ajax, which of them have you tried and why are they not sufficient to resolve your problem?