I create an Ajax request (below) which passes data to the server with the information I need.
function verify(key) {
$.ajax({
async: true,
type: 'GET',
url: '/zonepass/'+key,
data: {
'zone_key': key
},
success: function(res){
//alert('Sent a text message successfully to ' + res);
}
});
}
I handle the Ajax request on the server side where I use the passed in data to query my Firebase DB to get other relevant information.
I then try to render the view page that I want to navigate to using res.render('verify',{zone: obj, key: zone_key}) where verify is another .ejs file that I want to navigate the user to and the JSON object is the data that I want to pass to that template.
My code is not rendering the view page and I'm not sure why. I console logged all the data on the server and all the data is being pulled properly but then my view page never navigates to the verify ejs file...
app.get('/zonepass/:id', function(req,res) {
var zone_key = req.param('zone_key');
var zone_obj = firebase.database().ref('zones').child(zone_key).once('value').then((snap) => {
obj = snap.val();
res.render('verify',{zone: obj, key: zone_key});
});
});
res.render will not work with an ajax request, response from ajax call is returned and accessible inside the success function, but res.render will not work also res.redirect will not work with ajax request.
So you need to submit your request using a form or redirecting on frontend to that route, which is technically also a get request but without ajax example:
Using only HTML:
Verify
Using javascript:
function verify(key) {
window.location.href= "/zonepass/"+ <your id> + "?zone_key=<your zone key>"
}
Also in your NodeJS route you can access id using req.params.id and zone_key using req.query.zone_key, so your server code will be:
app.get('/zonepass/:id', function(req,res) {
var id = req.params.id;
var zone_key = req.query.zone_key;
var zone_obj = firebase.database().ref('zones').child(zone_key).once('value').then((snap) => {
obj = snap.val();
res.render('verify',{zone: obj, key: zone_key});
});
});
BTW you will need to handle inside the verify view, if the key is not verified, example you show an error or message in verify view, that the key is not correct ... or any message related to your logic
Related
I am trying to use ajax to send data from client-side to server-side without refreshing the page.
I am using this ajax code inside my pug file -
script.
$(function() {
$('#form1').submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {form.serialize()}
});
});
});
I am using the same URL and the method(which is POST).
Router file:-
const express = require("express");
const main_controller = require("../../controllers/main-controller");
const router = express.Router();
router.post('/form', main_controller.Send);
module.exports = router;
Controller file:-
const data_model = require('../../models/data-model');
exports.Send = (req, res, next) => {
data_model.find((err, data) => {
res.render("./customer/form1", {
pageTitle: "Form1",
data: data
});
});
};
I want to filter the data I am sending above. In the form, I have dropdown boxes in which I'm displaying the data, when the user selects something, I am sending the option he chose to the server.
In the server, I am filtering data based on the option that was selected. I want to send the filtered data back to the client-side, but I am not able to.
In jQuery, you can use the success callback or the .done Promise Resolution for accessing data sent back by the server for further processing. Please have [a look here at the documentation][1] for further examples on how to do this.
[1]: https://api.jquery.com/jquery.post/#:~:text=%24.post(%20%22test.php%22%2C%20%7B%20name%3A%20%22John%22%2C%20time%3A%20%222pm%22%20%7D),%7D)%3B
I am trying to send a JSON response, and redirect the page at the same time. It is not happening. Is there any way to redirect in Express.js while sending some JSON response to client? I want to use this JSON response to render the value to the redirected HTML page.
My Code -
//I tried using the below code. But it is not working
const app = express();
app.get('/user', authenticationMiddleware, (req,res) => {
res.send({name : "StackOverFlow", reason : "Need help!"});
res.redirect('/user/me');
})
Expected result :
I should get the {name : "StackOverFlow", reason : "Need help!"} as response (I will use fetch() to get the response) in the redirected client side HTML.
What you'll want to do is setup your response object to look something like the below:
res.send({name : "StackOverFlow", reason : "Need help!", redirect_path: "/user/me"});
And then in the function callback on your client (where you're making the fetch request), you'll want to pickup the value of response.redirect_path and pass it into a JS redirect method.
You could use something like:
location.href = response.redirect_path
Example usage (on the client-side)
fetch("http://yousite.com/endPoint")
.then((resp) => resp.json()) // Transform the data into json
.then(function(response) {
if (response.redirect_path) { //optional check to see if a redirect path exists
location.href = redirect_path;
}
})
})
Bear in mind, I'm assuming that the argument passed in your fetch response callback function is called 'response', if it is 'res' or something else, you'll have to adjust the code above accordingly.
You should send json response to client side and under success function of your ajax call use window.open(redirecturl)
Let me know if it didn't help
I'm using Node + Express. On page load, the app calls a remote database, gets data and sends it to a handlebars template. All this is done server side. But I'd like to be able to have this same JSON data be available for the client to interact with. How do I do that?
Example, server displays a table of ten records. I want the client to be able to click on one record and get a details view of just that one record. Thanks.
Here's the code:
app.get('/', function(req, res) {
getDataFromDatabase(function(data) {
data = JSON.parse(data);
res.render('index', {
stuff: data
});
});
});
function getDataFromDatabase(callback) {
var options = {
hostname: this.hostname,
path: this.path,
port: 80,
method: 'GET'
}
http.request(url, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
callback(data);
}).on('error', function() {
console.log("error");
})
}).end()
}
How do you get the data as a variable accessible to the client, on
page load, when the server is doing all of the work? Do you have to
make a redundant call from the client and get a "copy" of the data?
- June March
If you don't want to make an AJAX call after the page loads to get at the data, you can send it along with the rest of the page inside of a script tag. Not sure which template engine you're using so the following is sudo code (might be Jade, I don't know). Do something like this in your template:
script var data = JSON.stringify(stuff); // <- horrible variable name btw
If you can successfully create a script tag in your template, and initialize a variable with the data you want to pass to the client, you shouldn't have to make another call to the server.
I have a node.js express application which is trying to make a post request and query the contents of a database. I am trying to execute the post request without have to redirect the user from the form page or reloading the page.
index.jade
form.well(id="newEntryForm", method="post", action="/addEntry")
label Key:
br
input(name="key", id="key", class="new-entry", type="textbox")
br
br
label Value:
br
input(name="value", id="value", class="new-entry", type="textbox")
br
br
button.btn(type="submit") Add Entry
app.js
app.post('/addEntry', function(req, res){
//database query
});
This ends up redirecting me to the URL localhost:3000/addEntry. I know I can add res.redirect("/"); within the callback for the post method, but that will reload the page. How do I accomplish this without reloading the page?
EDIT
I added a javascript method to execute on submitting the form, but it ends up appending the POST request parameters on the URL bar. How do I avoid this?
Javascript method
$(function() {
$('#newEntryForm').submit(function() {
var data = {key: 'a', value: 'b'};
// build a json object or do something with the form, store in data
$.post('/addRule', data, function(resp) {
alert(resp);
console.log("post response: " + resp);
// do something when it was successful
});
});
});
As a comment said, you need to use client side javascript+ajax.
$(function() {
$('#newEntryForm').submit(function(event) {
event.preventDefault(); // Stops browser from navigating away from page
var data;
// build a json object or do something with the form, store in data
$.post('/addEntry', data, function(resp) {
alert(resp);
// do something when it was successful
});
});
});
I am new to Node.js and this is my first project with it.
I have made a node.js file named test.js. It has an array say a.
Now I want to make a HTML file that calls this test.js on button click event. Then get the data from that file and publish it on a table in the HTML file.
I have already written the node.js file and I can see the results on console.log(a). But I cant understand how to send this array to HTML when it will ask for it.
Meanwhile, I googled and made up some code. The request reaches the server but I always get error response from server. Why so?
Client Side -
function fetch() {
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8888",
data: 'China',
datatype: 'json',
success: function (data) {
alert("hi");
var ret = jQuery.parseJSON(data);
$('#q').html(ret.msg);
},
error: function (xhr, status, error) {
alert("hii");
}
});
Server side :
http.createServer(function(request, response) {
console.log("Request received");
response.writeHeader(200, {"Content-Type": "application/json"});
request.on('data', function (chunk) {
console.log(chunk.toString('utf8'));
consol.log(result);
response.write(JSON.stringify({data : result}));
});
response.end();
}).listen(8888);
I can see China on the console.But I dont get back the result array back to the client. Here result is an array and I get its value on the console. Just that I dont get it back to the client. Any help ?
You should start by setting up a server to serve requests. I use expressjs for this - http://expressjs.com/
This will allow you to run nodejs as a web application.
Setup a route in express JS to serve your data - http://expressjs.com/api.html#express
var express = require('express');
var app = express();
app.get('/data', function(req, res){
res.send('hello world'); //replace with your data here
});
app.listen(3000);
Open up a browser, and type in http://MY_SERVER_ADDR:3000/data and you should see your output there.
Next, you'll need to attach an event handler to your HTML file that will trigger a $.get() request when it is triggered. Add the previous url to your data in your $.get call and do something with it.
$('.my_selector').click(function(){
$.get('http://MY_SERVER_ADDR:3000/data', {}, function(data){
console.log(data)
});
});
That should get you going.
After wrestling with the same question, i found that this is exactly where a template engine comes into the node-picture.
EJS solved it for me, but there are many more available.
This article compares 10 template engines.