res.render sends data back in String format - javascript

I am developing an app with the node, express, and mongoose. In my login module, res.render() the function sends the code back to the client side ajax call as string format data. Whereas I wanted it to render a particular view. ajax call is post type call. I can see the entire HTML in string format in success field of ajax.
I did search for similar problem and solutions, but I couldn't find any. Let me know what I am doing wrong.
Client Side :
$.ajax({
type: 'POST',
url: '/login',
data: userDetail,
success: function(data){
console.log(data);
},
error: function(err){
$("p").text("Invalid User Details")
}
});
Server Side :
app.post('/login', urlencodedParser ,function(req,res){
console.log(req.body);
User.find({name : req.body.name , password : req.body.pass},function(err,data){
if (data.length != 0){
Todo.find({},function(err,todo){
if (err) throw err;
var token = jwt.sign(req.body,config.secret,{
expiresIn : '1h'
});
res.render('todo',{
todos : todo,
token : token
});
});
}
else
res.status(401).json({ msg : "Invalid User" });
});
});

Ajax calls do not, by themselves, change what is displayed in the browser. They just fetch data and your Javascript code them decides what to do with that data. This is true no matter what type of Ajax call it is, GET, POST, etc...
If you want to change the current page to show the content you fetched with Ajax, then you have to insert that content into the current page yourself.
Or, in the case of a POST, perhaps you want to submit an HTML form and then the browser will render the content that comes back from that form post for you, but an ajax post will not change what the browser displays at all.
Submitting an HTML form can be done either via Javascript or via native user actions (without any Javascript). But, for the browser to process the result for you, it has to be the browser submitting the form, not an ajax call sending the form. If an Ajax call sends the form (as in the code you show), then the result just comes back to your Javascript and it's up to your Javascript to decide what to do with that result (insert it in the page, etc...).

Related

Recieving data sent by ajax.post

I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.
You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);

How to make a request using jQuery to a django server to refresh infos on page

I made a website in python using Django. My site allows you to control lights while indicating if the light is on or not.
I'm looking for a solution that could make a simple request with data to the server and send data back to the client without updating the entire page but only a part of it.
My ideal would be for the client to make a request to the server with identification data. Then, the server returns the updated data that the user is allowed to have.
Is that possible to make a JavaScript to do that ? And the server, how it can return data to the client ?
You can Use jquery AJAX for send request and get a response and Update an element or part of the page you can read more about it in :
W3schools
or :
jquery.com
AJAX function I use for PHP project:(Just for example)
$.ajax({
type: "POST",
url: Url,
data: InfoData, // data if you want to send for example InfoData={dataName: variable} or you can set this = '' if you don't want to send data
datatype: "html",
success: function(result) {
console.log(result);
}
});

Simple POST request using jQuery leads to unexpected redirect

I've got a few similar POST request on a website. In one case, the request is working (data is stored on the server), but then, there's an unexpected redirect. I send/receive data using jQuery. On the backend, I use the PHP framework Laravel.
Let's say I'm on myapp.dev/clients/123. Then I click the store-data-button and data is sent to/received from the server (Let's assume $('#resubmission_note').val() === 'abc'):
// AJAX request
$('#store-data-button').on('click', function() {
let ajaxRequest = $.ajax({
url: '/resubmissions',
type: 'POST',
data: {
// An integer, some text, and a date
'client_id': $('#id').html(),
'resubmission_note': $('#resubmission_note').val(),
'resubmission_due_date': $('#resubmission_due_date').val()
}
});
ajaxRequest.done(function(returned_id) {
// Removed all code here for testing. Browser still redirecting.
});
});
But then the browser is redirected to myapp.dev/clients/123?resubmission_note=abc.
The network tab in Chrome devtools says
Name:123?resubmission_note=abc
Status: 200
Type: document
initiator: Other
There's data appended in the URL, that should only be the case with GET request, AFAIK. I checked whether some other JavaScript code might interfere, but couldn't find store-data-button or resubmission_note in any unexpected files.
Any advice on how to fix the problem or how to debug it?

Why is python requests getting different results than Ajax

I am trying to write a Python script that logs into website for me and downloads my messages. I'm using the the "requests" library and succesfully able to log in with a session
The website uses js/Ajax to download the actual messages client side after the messages page has been loaded, and uses pagination to achive an infinite list of messages effect.
The messages page url is in the form of https://website.com/messages. and that page contains an Ajax call that retrives the messsages like this:
$.ajax({
url: '/messages?mailbox=' + mailbox + optional params
}).done(function(data) {
urlLazyLoading = data.next_page_url;
$.each(data, function(i, v) {
//from this point on, data for each message can be
//accessed using the v object as such:
//v.sender, v.date, v.last_message, etc
//and the <ul> element is populated with '<li>'s
But when I try to access the same url in python (after I've loggedin) as such:
session.get('https://website.com/messages?mailbox=inbox')
instead of getting a json response with the messages data, I get the same/original messages page.
the only parameter passed to ajax in the code above is url, so by defult it should be just making a simple GET request, which is what I'm doing.
Is it possible that maybe somewhere else in the code ajax is being set up to default to POST or have some other non-default settings?
or is the server somehow detecting that one request is coming from ajax and the other from sessions? maybe using user-agent?
Got it!
Ajax sends a header value by default:
{'X-Requested-With': 'XMLHttpRequest'}
I added that in and viola
headers = {'X-Requested-With': 'XMLHttpRequest'}
r = s.get("https://website.com/messages?mailbox=inbox",headers=headers)

Ajax Request in Node - Avoid Page Reload

I have an ajax request being called on form submit. The idea is to save a user's account information without a page reload, and give them a handy flash message to let them know the save was successful. I have no problem saving the data, but I do have a problem with avoiding a redirect on the POST (to a white page with the response data). Here's what I have:
In my Jade view
$("form").on("submit", function (e) {
e.preventDefault(); // prevent page reload
$ajax({
type: "POST",
url: '/account',
data: $("#accountForm").serialize(),
success: function() {
// can req.flash even be used here? How might it be?
req.flash('info', {msg: 'Your profile has been updated!'});
}
}
}
In my controller
exports.postAccount = function(req, res, next) {
var userData = req.body;
userData.id = req.user.user_id;
var updateUserCallback = function(err) {
// This is where everything falls apart
// Theoretically this should run the success handler in the ajax response
res.json(true);
// Any response I send changes the view to a white page with the data, e.g.
// res.send(anyData);
// Flash also doesn't seem to work, which seems weird...
req.flash('info', {msg: 'Your profile has been updated!'});
}
// Successfully saves the data, no problems here
UserModel.updateUser(userData, updateUserCallback);
};
Normally in the updateUserCallback I would just render the account view, but that defeats the purpose of ajax. I want to save the user's data without a page reload/redirect, while letting them know that the ajax function completed successfully (or didn't) via req.flash (flash module).
Basically any res.send() or res.json() call puts that data into a plain white page (no view). I suppose that I'm fundamentally misunderstanding how ajax works, but I've followed other examples for jQuery ajax calls in Node and have not been able to avoid the 'white page' problem.
Node:
var updateUserCallback = function(err) {
return res.send({
message: "Your profile has been updated"
});
}
Client-side JS:
success: function(response) {
// can req.flash even be used here? How might it be?
// Nope
//req.flash('info', {msg: 'Your profile has been updated!'});
$('#someModal').show().html(response.message); // just a sample implementation
}
Instead of using the form submit, you can use simple button click so that page will not get reloaded.

Categories