Use Ajax return value in Jade file - javascript

I am using ExpressJS together with the Jade template engine. I am trying to do the following:
In a Jade file, I extract a variable which I need in a JavaScript file. In this JavaScript file, I send an Ajax request to the Express server. This returns some data and I would like to put this data in another variable which I can use again in my Jade file.
Here is my code:
Jade file:
script.
var userID = '#{userObject.ID}'; //Extract variable
script(src='/javascripts/account.js') //needed in this file
p
| #{papersObject} //This should be the result from the Ajax request
Ajax request:
$(document).ready( function() {
$.ajax({
url: '/accountdata',
/* jshint ignore:start */
data: {'personId': userID},
/* jshint ignore:end */
dataType: 'JSON',
success: function(data, status, jqXHR) {
var papersObject = JSON.stringify(data.result);
}
});
});
app.js:
var accountData = require('./routes/accountdata');
app.use('/accountdata', accountData);
Route:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
data = //Some database function
res.send({result: data});
});
module.exports = router;
Why is #{papersObject} not showing on my page? How can I get this to work?

Your server side code and client side code run on different computers. The Jade template is processed before the Ajax request is even sent.
If you want to add the data to the page, then you need to use DOM manipulation to do so.
e.g. with append()

Related

Unable to make a GET request with AJAX under Node.js when using NGINX

Despite I have learned and implemented AJAX request with Node on my local server. I am finding that the requests that I created on my local server, just does not work at cloud server.
When I use AJAX to request data to the server (Node), the request does not get to the server because of the URL (or I think so).
Node Code:
app.get("/",function(req,res){
app.use(express.static(__dirname + '/'));
app.get("/mypath/",function(req,res){
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data);
});
});
Javascript Code:
$.ajax({
url: 'http://localhost:3000/mypath/',
type: 'GET',
data: {//some data to use on the server},
dataType: "json",
complete: function(data){
//some stuff with the transformed data
},
});
The code above works in the local server (my pc). But not in the cloud one, I had some problems trying to the server static files with NGINX and Express, but I was able to figure it out.
Do you think that given the way I am serving the static files and that I am working in the cloud server, I should use AJAX request in a different way when we are trying to communicate through an URL?
Console Log:
Console Log after using Marcos solution
EDIT: Code from jQuery AJAX and Node Request
Node Set-Up:
var express = require('express');
var app = express();
var request = require("request");
var db = require('mysql');
const path = require('path');
var http = require("http").Server(app);
var io = require("/usr/local/lib/node_modules/socket.io").listen(http);
http.listen(3000, 'localhost'); //At the end of everything between here and the code.
GET Node Code:
app.use(express.static(__dirname + '/'));
app.get('/reqData',function(req,res){
//I never arrive here
console.log("print that I am here");
transform(req.query.selection1,req.query.selection2,function(){
res.json(data); //data is transformed globally
});
});
Ajax:
function requestData(){
$.ajax({
url: 'http://localhost:3000/reqData',
type: 'GET',
data: {//Some stuff to send},
dataType: "json",
complete: function(data){
do(data);
},
error: function(e){
console.log(e);
}
});
}
New Console Log:
Chrome Console Error
The main issue you have, is how you're defining your routes, you will be unable to reach /mypath/ until you perform a request first to /.
You should not define your routes that way, each route should be defined individually, and not in a nested way.
app.get('*', (req, res, next) => {
// Set your cookies here, or whatever you want
// This will happen before serving static files
next(); // Don't forget next.
});
app.use(express.static(__dirname + '/'));
app.get('/mypath/', (req,res) => {
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data); // make sure it is defined.
});
And your route app.get('/') conflicts with express.static(__dirname + '/'), so you should just remove it if you're only serving an index.html file, which seems to be your case.
Then in your $.ajax you should add the protocol to the URL.
$.ajax({
url: 'http://yourdomain.com/mypath/',
// url: 'http://localhost:3000/mypath/',
/* ... */
});
Now, supposing you have everything else setup correctly, you will be able to access /mypath

AJAX and Node JS/Express post not sending or receiving data

I am new to Node and I am trying to use app.post, everything works fine including the console log whenever the action is executed but it does not receive the data sent by the AJAX from main.js.
Here is a snipper of main.js which sends it:
$.ajax({
type: 'POST',
data: '{"title":'+ this.messageInput.value +'}',
url: 'http://localhost:3000/send'
});
Here is my config.js which should be receiving the data:
app.post('/send', function(req, res) {
console.log(req.body);
console.log('Send button clicked');
});
I am using bodyParser with express. So that is why I am using req.body. When I console log req.body I get undefined. When I console log req, I get a list of data but not what I sent.
I hope someone can help!
It's good that you are using body-parser, but have you defined a JSON parser in your app?
You didn't paste all of your code so add this if you don't already have it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
console.log(req.body);
console.log('Send button clicked');
})
Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)
var myData = {};
myData.title = this.MessageInput.value;
Then in your Ajax code, just use myData:
$.ajax({
type: 'POST',
data: myData,
url: 'http://localhost:3000/send'
});
Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out

How to get data by hitting an url and then rendering it to html using node.js and express.js

I have a javascript file, in that file i am using node's 'request' module to hit an url and get data, process it and send an html response to the client. Here is the glimpse of that file
Now i am using express.js for this purpose, and i am sending the values of variables through res.render function but i don't know how to access these in my jade file.Here is the my index.jade and this is my index.js file
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res,next) {
console.log("hello everyone I am here!!!!!");
res.render('index',{locals:{title:'Results',pass: 'siddharth'}});
});
module.exports = router;
Thanks in advance
Just use them as you send them. Example:
Render:
res.render('index', {title: 'Hello, World'});
View:
doctype html
html
head
title= title
body
h1= title
NOTE: The object you give to your view is:
{
locals: {
title: 'Results',
pass: 'siddharth'
}
}
So in your view you use them like this:
title= locals.title

express node.js making a get request to another server from node route

So the client makes a get request using a button on the index page. This sends some information to a route which has been set up as follows:
app.js
var route = require('./routes/index');
var button = require('./routes/button');
app.use('/', index);
app.use('/button', button);
The request is sent from a client-side directory to the node framework whenever someone presses the button. If the request is sent to 'localhost:port/button', then the button.js file mentioned above will receive the request. So in the button.js file we have something like the following:
var express = require('express');
var router = express.Router();
var someData = '';
router.get('/', function (req, res, next) {
//make a get request here such that someData
//receives whatever the request returns from another
//set up framework(i.e. Spring...)
someData = getRequest('some other URL');
res.send(someData);
};
module.exports = router;
The problem here is that the getRequest('some other URL') within the router get request never receives any information.
Also (as a side-note), I cannot seem to find in the express API as to why we have
router.get('/')...
instead of
router.get('/button')...
to access and make requests to the button page.
Any help would be very much appreciated!
You want to make a request to some other REST API running somewhere else right?
You can use node-rest-client for that.
I guess you are confusing what is server code and client code or do I´m missing something?
I´ll try to explain the way it works:
Server code:
var express = require('express');
var router = express.Router();
var someData = '';
router.get('/yearStations/:id', function (req, res, next) {
//make a get request here such that someData
//receives whatever -the id parameter- the request returns from another
//This is express.js
someData = getYourDataFromDataBase(req.params.id);
res.send(someData);
};
module.exports = router;
Client code:
JS (angular.js)
$scope.getInfo = function() { //here you make the GET call to the server
$http.get("http://localhost:XXXX/yearStations/Spring").then(
function(success){
alert(success.data);//this should be your data
});
};
HTML
<button ng-click="getInfo()">getInfo</button>

Angular $remove() and express delete()

How can I processed http DELETE request with express.js, created by angular-service's default $remove() method?
I have working post method:
On client (specifically inside angular controller):
$scope.obj.$save();
On server:
myRouter.post('/', function(req, res) {
var param = req.body.some_parameter; // got it fine
});
But it doesn't work with delete :)
On client:
obj.$remove();
On server:
myRouter.delete('/', function(req, res) {
//this route will be called, but I want get obj parametr like in post method
//can I do that? Or I shoud use request with parameter instead (?param=val)
//here I get undefined
var param = req.body.some_parameter;
});

Categories

Resources