I'm brand new to express and node, so please bear with me :D
i have an index.ejs file. I need to pass a string from my index.ejs file, to my viewActivity.ejs file. That string will then be used in the javascript portion of my viewActivity.ejs file. I'm not really sure how to go about this though. Is what I want to do even possible? Or do I have to do this via another file and not just directly view to view ?
here is my code. I want to pass the "stringToPass" to another view when a button is clicked.
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results){
for (var i in results) {
var title = results[i].get("activityTitle");
var stringToPass = results[i].id
}
}, error: function(error) {
console.log("Query Error:"+error.message);
}
});
}
So far I've learned that express acts as the request handler. E.g.: pass you the file or anything based on the given request.
As soon as the request has been finished being handled, express would not know what the client does with the given result. Hence, once it sent the html file or json file or other request has been responded, all the remaining activities will be handled by a client side script that talks back to the express server in other form of requests. UPDATE: you can make this client side script to extract a DOM element and pass it onto your follow up request (when a user click a submit button, etc) that is handled by a different route.
Related
js and javascript... i getting problem in how send array value from client side .js file to server side app.js into post request.
var = testParamterName=[],testParameterValue=[];
$("#Table1 tbody tr").each(function(rowinex){
// this basically gets the 2 column values that i require
var i=0;
$.each(this.cells,function(callIndex,cell){
if(i==2) //parameter value
{
testParamterName.push(cell.textContent);
} else if(i==3)
{
testParameterValue.push(cell.textContent);
}
i++;
});
i=0;
});
i am getting values from a table using jQuery in a file called test.js
after saving the table values into two array namely 'testParameterValue' and 'testParamterName'
now i want to send these 2 array values to my server side .js file app.js
i used the module.exports = {testParameterValue , testParametername};
but this gives an error saying module not defined..
i have tried searching the web couldn't find the solution to my problem ... the closest solution i found was that .... cannot run module.exports into files that run in the browser.
i have skipped the code where i handled a click event for submit
please help me ...Thanks in advance :)
First of all you need to setup your server-side application with e.g. NodeJS and express. Your basic app will listen on the specific port, like localhost:3000. Then you need to request this URL with your client-side JavaScript code.
This issue is very well explained over here:
How to process POST data in Node.js?
Summary of my website: A user fills in some information which after hitting "submit" the information is submitted to the backend via AJAX. Upon the back end receiving the information, it generates a DOCX using the information and serves that DOCX file back to the user.
Here is my AJAX Code in my HTML File
$.ajax({
type:'POST',
url:'/submit/',
data:{
data that I submit
},
dateType: 'json',
success:function() {
document.location = "/submit";
}
})
My Views Function for /submit/ that uses send_file to return file
def submit(request):
#Receive Data
#Create a File with the Data and save it to the server
return send_file(request)
def send_file(request):
lastName = get_last_name() +'.docx'
filename = get_full_path() # Select your file here.
wrapper = FileWrapper(open(filename , 'rb'))
response = HttpResponse(wrapper, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=' + lastName
response['Content-Length'] = os.path.getsize(filename)
return response
This has worked flawlessly for sometime now. However I started having problems when I increased the amount of "web-workers"/processes from 1 to 4 in my hosting account. Whats happening is a different web-worker is being used to send the file, which is creating a new instance of the site to do that. The problem with that is that the new instance does not contain the file path that is created with the web worker that creates the file.
Like I said, this worked flawlessly when my webApp only had one "web worker" or one process. Now I only have roughly a 50% success rate.
Its almost like a process is trying to send the file before it has been created. Or the process does not have access to the file name that the process that created it does.
Any help would be much appreciated. Thanks!
Code Trying to send path_name through request and then back to the server.
Submit View returning file info back to ajax.
def submit(request):
# Receive DATA
# Generate file with data
lastName = get_last_name() +'.docx'
filename = get_full_path() # Select your file here.
return HttpResponse(json.dumps({'lastname': lastName,'filename':filename}), content_type="application/json")
Success Function of AJAX
success:function(fileInfo) {
name_last = fileInfo['lastname']
filepath= fileInfo['filepath']
document.location = "/send";
}
So can I get the fileINfo to send with the "/send" ?
Each web worker is a separate process. They do not have access to variables set in another worker. Each request could go to any worker so there is no guarantee that you'd be using the file name that was set for a particular user. If you need to transfer information between requests, you need to store it outside of the worker's memory - you could do that in a cookie, or in a database or a file.
I want to pass data to the js file. however cant get is to work.
js='article.js';
function loadjs(js){
$.get(js,{ name: "test" });
}
article.js
alert(name);
if i do alert('test'); i get a response from the file so i know it works.
also cant use globals.
is there a simple way to send the data to the file and show it?
EDIT to clarify
(yes i can use angelar but i dont)
Onload it triggers 'pagina' with all short of variables. (its dynamic).
all the 'php/html' files are loaded.
and you get what you can see in the link. example
hoverever when i click on a row i want function pagina(); to load the content of the row so far so good. however to show the data that i want. I want to send a ID to the JS file and use a $.post (php) in the JS file to get data json. if i set a ID in $.post id=1 directly its works.
so to not let it be more confusing. i want to send a id to a js file JS $.get or $.getScript.
function pagina(menu,frame,vars,crum,js,togglezoeken,voorwaarden){
'use strict';
if(!menu){$('#frame').show();}
if(menu){
$('#loader-zoeken').hide();
$('#loader-bijwerken').hide();
$('#loader-pagina').show();
$('#menu').hide();
$('#frame').empty();
$('#menu').load(menu+vars,{noncache: new Date().getTime()}, function() {$('#menu').foundation();});}
if(crum==1){$('#breadcrumbs').load('/opbouw/frames/breadcrumbs.php?'+vars,{noncache: new Date().getTime()}, function() {});}
$('#frame').load(frame+vars+'&crum='+crum,{noncache: new Date().getTime()}, function() {
if(togglezoeken){$('#uitgebreidzoeken').toggle();}
if(crum==1){$('#breadcrumbs').show();}else{$('#breadcrumbs').hide();}
if(js){
$.get( js,{ name: "test" });
}
else{
$('#loader-pagina').hide();
$('#menu').show();
$('#frame').show();
}
//if(voorwaarden==1){popup('/opbouw/frames/voorwaarden.php','','/opbouw/js/voorwaarden.js');}
$('#frame').foundation();
});
}
You can't do it that way. $.get is used for AJAX/HTTP(s) requests and your file in that way won't accept the data sent to it.
To achive this you have to use a server-side endpoint on your article.js.
Lets say:
function loadjs( js ) {
$.get(js, { name: "test" });
}
And you make a call of loadjs function:
loadjs('article.js');
On your server you have to have an server-side endpoint directing to a request: /article.js:
You can achieve this by using PHP or express for node.js:
router.get('article.js', function(req, res, next) {
res.json( req.query.data );
});
Or in PHP (note in Apache you have to use mod_rewrite and enable it with .htaccess or in your virtual host configuration):
$req = $_SERVER['REQUEST_URI'];
if($req == 'article.js') {
echo json_encode(array('data' => $_GET['data']));
exit(0); // end the script here
}
In either way used from above you have effectivelly sent a data to your script / endpoint and you can handle it further.
Although your loadjs function just sends a request and doesn't handle a response, you can do the following with a callback function in $.get:
$.get(js, { name: "test" }, function(data) {
alert(data); // you will alert the data from the JSON response
});
Sadly, you haven't described what you actually need and this is as far as I can help you with so far.
The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html.
router.post('/index', function(req, res, next) {
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
$(document).ready(function() {
var output = document.getElementById('cost');
output.innerHTML = toCost;
});
res.location('/');
res.redirect('/');
})
I receive the following error and jquery is loading fine.
$ is not defined
Admittedly this is an over-engineered node/express app. The code snippet lives wrapped in a route file, inside a post request.
How do I get my value onto the html?
Jade layout
extends layout
block content
form(...)
div#cost
The normal way to do this would be as follows:
router.post('/index', function(req, res) { <<< 'next' removed (only needed if using middleware)
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});
Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this:
indexTemplate.jade:
extends layout
block content
form(...)
div#cost #{cost} <<< adds the cost variable to page
Then the value of toCost will appear in the resulting page.
No jQuery is required on the server side.
jQuery is made for DOM manipulations and there's no DOM on a server.
Try using 'jsdom'.
jQuery is made for client side scripting, not for server-side client manipulations.
It seems that you're trying to make changes on client-side from your backend. It doesn't work that way.
You could create a variable on backend for storing calculation result. And get this value by get query from client-side
You're tring to reach DOM (that is on client side) from NodeJS on a server side. It doesn't work that way.
I have a Post-form in my ejs-template that passes one object via Ajax/post without the page being reloaded. The handler in my app.js then saves the data into a data.json. All of this is working perfectly.
My only concern is that node seems to be requiring the json file only once, I have already tried using setInterval() which made no difference at all.
The desired functionality is that the server reloads the data.json after every other submit of my form. Furthermore I have an iframe where the loaded data is displayed. This should happen on the fly therefore without any refresh of the page.
For your above comment socket has nothing to do with it.
To answer your question , you can keep that JSON in memory , creating that object as a global object accessible by every part of code (files).
code example ->
app.js -
global_json = require('../path/myJSON'); //please note that I am not using var here to make it global
//Rest of the code
file1.js -
module.exports = fun(req, res) {
global_json.something = req.body.something;
//global_json accessible in every file
}
Alternative
If this is not the use case, then you can read and write file in every request (from post), although file reads/writes are slow but wont be the bottle neck in case of node.js server
function formpost(req, res) {
var data = req.body;
fs.writeFile('filename.json', JSON.stringify(data), cb);
}
//And same with reads