Server sends data to client - javascript

In my express project I want my server to send a JSON object to the client. The client uses a script to display the data it recieves and so I dont want to the data sent from the server being seen on the screen directly, I want it to go through the javascript first.
I tried many ways to send any data and non was successfull:
client:
$.get('http://localhost:1337/', {mydata: 'content'}, function(response){
console.log(response);
});
or
$.ajax({
url: 'http://localhost:1337/',
data: {
mydata: "content"
},
dataType: 'json',
success: function (json) {
console.log(json);
},
error: function (jqXHR, error, errorThrown) {
console.log(error);
},
type: 'GET'
});
server:
app.get('/', function (req, res) {
res.render('main',{data:'text'})
});
or
app.get('/', function (req, res) {
res.render('main','text2')
});
Is there a way to send data to the client that will go first to the javascript in the sended page?
Thank you!

On your server, use res.json({data:'text'}); instead of res.render(...) to send json. That should do the trick.
Update:
If you want to build a single page application with multiple ajax requests you should use different routes for those. One will send the page and the other the data.
However, if your application is small and simple, you could continue doing what you did, but get the data via javascript variable instead of an ajax request. For that in your template you'll have to do something like that (assuming it's jade):
script(type='text/javascript')
var local_data =!{JSON.stringify(data)};
The page will be rendered with the following HTML:
<script type="text/javascript">
var local_data = {"data":"text"};
</script>
You than in your script can do the following:
//Your javascript
function displayPage(data){
//display logic here
console.log(data);
}
displayPage(local_data);

Related

jQuery put request from node js (using to upload JSON file to myjson.com)

I am a beginner in javascript. I am able to get json object from http://myjson.com/api in my html page using ajax by using:
$.getJSON("https://api.myjson.com/bins/bjm28", function (data) {
$.each(data, function (index, value) {
console.log(index,value);
});
});
I wish to update the same json file with different values from my app.js which I run using nodejs.
I tried https://www.npmjs.com/package/ajax-request and "Update a json" column in http://myjson.com/api
var request = require('ajax-request')
data={
"Man":960,
"Woman":40
}
request({
url:'https://api.myjson.com/bins/bjm28',
type:'PUT',
dataO:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(dataO, textStatus, jqXHR){
}
});
All the methods I find are used for javascript running in browser (not nodejs)
Is it possible for me to update this json file through nodejs?
I am trying myjson because initially I was unable to load local json/txt to html pages due to "Cross origin request errors.."
My aim to control my html webpage through nodejs (lotion.js) for dapp.
For your specific question/example you can use the NPM Request module: https://www.npmjs.com/package/request
You should do the following:
let request = require("request");
let requestOptions = {
// your options here
};
request.get("https://www.example.com", requestOptions, function(error, response, body)
{
// process the response here
};
In the Request module documentation you can also find examples to POST information.
Hope this can help!

How to stay at the same page after submitting post request with Express?

I know this might be a simple question but I just didn't find the solution I want. I write a post route with express. like this:
app.post('/search', function(req, res){
// Some code to get data from req and save data to db
// Then want to stay current page.
});
My html:
<form action="/search" method="post">
<input value="name" name="marker[name]">
<input value="address" name="marker[address]">
<input value="rating" name="marker[rating]">
<button id="favo-button" type="submit">
Submit
</button>
</form>
When user click submit button, the data sent through req to the post route, and there insert to db. Then I want the page not direct to anywhere but stay current page. I tried some ways but not handle it very well. what I tried:
in the route,
res.render('/search');
this makes the page re-render with the same view, but the page will flash because of the re-render.
don't do anything to the res in the route, then the page loading circle will never stop.
app.post('/search', function(req, res){
var data = req.body.marker;
// some code insert data to db
// then do nothing to res. The page will stay but keep loading.
});
Is there a way to just do nothing to res and stay, meanwhile not keep the page loading?
There are two ways to do this.
Return a 204 No Content response. (In Express: app.post('/search', (req, res) => res.status(204).send());, but that's basic HTTP you can do in any server-side code)
Make the request with JavaScript (i.e. Ajax, e.g. with XMLHttpRequest) instead of submitting the form
(You could also submit the form to a hidden iframe, but that's just an ugly hack).
You can do it in 2 ways:
1 - Do it using Jquery AJAX call, you need to write this code in your view page, not in controller or route of NODEJS App.
$("#YOUR_FORM_ID").on("submit", function () {
$.ajax({
url: '/search',
type: 'POST',
cache: false,
data: { $("#YOUR FORM ID").serialize() },
success: function (data) {
alert('Success!')
}
, error: function (jqXHR, textStatus, err) {
alert('text status ' + textStatus + ', err ' + err)
}
});
});
2 - By redirecting the request to the source request
app.post('/search', function(req, res){
//Do Something
res.redirect('/');//redirect to the page from where request came
});

Ajax request not working in loopback

I am beginner in loopback and working on Get Post in loopback
This is code on client side
var datas = 'Something';
$.ajax({
type: 'POST',
url: '/post',
data: datas,
dataType: 'text'
})
.done(function(data) {
console.log('Successful');
.fail(function(jqXhr) {
console.log('Failed');
});
and this is on server side(server.js)
app.post('/post', function(req, res){
console.log('This is DATA '+ req.body);
});
This is not working it gives me 404 not found or failed.
What am I doing wrong and Is there another method for get post in loopback?
the server side needs an server and listening a port.
the client side needs to listen another port.
so they are not in one domain and cannot get access to each other.
this called a "cross-origin requests"
check this for the solution:https://www.w3.org/TR/cors/
Your URL starts with '/'.
Whenever a URL starts with '/' it is treated as absolute URL.
Whereas, most of the time, web apps are bounded with a context root.
Try using URL without initial '/' and it should work.

Returning a string and passing into a separate HTML file from AJAX POST?

I have a simple AJAX POST from my Chrome Extension to my Node.js server. However I need to return a simple string as a response. Then pass this response into a HTML file. My code so far below:
postrequest.js
request("https://myserver", "post", {mydata})
.done(function(res){
console.log(res)
})
function request(url, method, data){
return $.ajax({
url: url,
method: method,
data: data
})
nodeapp.js
function sendStringBack(req, res) {
res.write("My string is here")
res.send()
}
I haven't a clue on where to start with the HTML code?
You could use
res.send("<html> ... </html>")
With the dots being your html.
You could send a template, express is very helpful for this:
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
Sending information over HTTP is what node.js was built for, there are hundreds of ways to do this.
You're trying to do two things here:
post something to your server
retrieve data from server
First we need to fix your ajax call:
$.post("https://myserver", { mydata }, function(response) {
// response has the data retrieved from the server
document.getElementById('the_parent_div').innerHTML = response;
//console.log(response);
});
Returning this function isn't working for the data. The call has to wait to retrieve data from your server.
Then your nodeapp.js
function sendStringBack(req, res) {
res.write("<html><body>Hello world</body></html>");
res.end();
}

How to catch JSON object when server and client on the same system

I made HTML page that have form, when submitting, it calls JavaScript by using this event handler.
onClick = operation(this.form)
and the JavaScript is:
function operation(x) {
//url:"C:\Users\jhamb\Desktop\assignment_1_18_1_13\question_3\ques\form1.html",
url:"http://localhost:8080",
$.ajax({
data:{
comment:x.comment.value, // information from html page
email: x.email.value, // information from html page
url:x.url.value, // information from html page
name:x.name.value, // information from html page
}
}).done(function(serverResponse){
alert("response is ready"); //here you can handle server response
}).fail(function(err){
alert("ohhh!!! there is some error"); //here you can handle errors
});
//alert(obj.details[3].comment_value);
}
Now what I want is to communicate between server and client , that is on same system.
My code is not working. Now what can I do, please help.
first i don't think your server listens on port 8080, that normaly aport for the admin software.
second you have to put the url inside the ajax request
function operation(x) {
//url:"C:\Users\jhamb\Desktop\assignment_1_18_1_13\question_3\ques\form1.html",
$.ajax({
url:"http://localhost:8080",
data:{
comment:x.comment.value, // information from html page
email: x.email.value, // information from html page
url:x.url.value, // information from html page
name:x.name.value, // information from html page
}
}).done(function(serverResponse){
alert("response is ready"); //here you can handle server response
}).fail(function(err){
alert("ohhh!!! there is some error"); //here you can handle errors
});
//alert(obj.details[3].comment_value);
}
you shoul also add dataType (html or json), the sending type (post, get etc.) in the param list
Maybe it will help if you modify tour code slightly:
function operation(x) {
$.ajax({
url: "http://localhost:8080",
data: $(x).serialize(),
}).done(function (serverResponse) {
alert("response is ready");
}).fail(function (err) {
alert("ohhh!!! there is some error");
});
}

Categories

Resources