Can we send data from mongoDB to HTML? - html

I am working on a Mini Project where I have stored data coming from a form in my DataBase(MongoDB). Now I want to fetch data from MongoDB and want to add it to HTML(as a list) to display on the webpage.
I wanted to do this without using ejs or any other tool. Is this possible? If yes,then how?
(I have used Expressjs to create the server)

You would have to javascript in order to manipulate DOM elements on the page.
(see. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents)

You can fetch the data in your html then add it to your page by manipulating the dom.
This is might help you:
<script type='text/javascript'>
$(function(){
$.ajax({
url: 'http://localhost:28017/local/students',
type: 'get',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
console.log('success', data);
}
}).done(function(){
let output = '<div>'
$.each(data, function(key, data){
output += '<p>' + data.score + '</p>';
});
output += '</div>'
$('#list').html(output);
});
});
</script>
Also this response might be helpful:
REST AJAX request to mongoDB

Since you have mentioned you are using Expressjs, I believe you are also using an ODM like mongoose. Hence, you should create an api in your backend that fetches the data from MongoDB (see your ODM's documentation for it) and send request to that api from your front end, whose response should trigger DOM manipulation.
Here are some resources that might help you:
https://medium.com/swlh/how-to-build-simple-restful-api-with-nodejs-expressjs-and-mongodb-e59595091640
https://medium.com/#ingridf/flow-of-fetch-and-dom-manipulation-454af047b6c
https://developer.mozilla.org/en-US/docs/Learn

Related

Use JSON after caching through AJAX

I'm new in coding and currently creating a website that supports English and Russian languages. I want to change between them with no page reload, so I decided to use AJAX to achieve it and store information in JSON. I have a checkbox that changing my langString between EN and RU depending on checkbox state.
var langStr = "en";
$('#langsw').click(function(){
if($(this).prop("checked") == true){
console.log("Checkbox is checked.");
langStr = "ru";
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
langStr = "en";
}
});
And this is jquery code to perform AJAX part
$.ajax({
type:'GET',
dataType:'json',
url: langStr+".json",
cache:true,
success: function(data){
$('#meet').append(data.title);
$('#meet').append(data.hr);
$('#meet').append(data.subtitle);
},
error: function(data){
console.log("there is an error")
}
});
My JSON is
{
"title":"<h1 style=\"color:white; font-size: 42pt\">Name</h1>",
"hr":"<hr style=\"width:60%\">",
"subtitle":"<h1 style=\"color:#dbdbdb; font-weight:100\">Interactive resume</h1>"
}
and the second one is the same in Russian.
Now the question: I want to cache both JSONs and then use one of them depending on the state of the checkbox, but I don't know how to do so. If you have any ideas relating to other ways of achieving this I will be very happy to read them.
P.s English is my 2 language so forgive the mistakes.
You can save the information in localstorage (altough there is a limit of how much you can save there).
You can use this formula to save raw json into localstorage
localStorage.setItem('language-ru', data);
To get what is in localstorage you would use
const ru = localstorage.getItem('language-ru')
So you can check, if user has the right language in his localstorage and if there is nothing, you can download it with that ajax call.
You can read more about localstorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Unable to get data from json file on local server (port: 3000)

I am hosting an html page on localhost:8888 with a MAMP Server and I am trying to get some data from a JSON file which I am hosting on localhost:3000 on the 'categories' route. Firstly, I wanted to know is this possible ?
If it is not possible, is it possible for me to route the JSON data to another site. If it is possible, here is the script I have embedded in my HTML
<script>
$(document).ready(function(){
setInterval(test,500);
console.log("document ready");
alert('page ready');
});
function test() {
$.ajax({
url:"HTTP://localhost:3000/categories",
dataType: 'jsonp',
success: function(json){
$("#Address1").html(json[0]["id"]);;
}
});
}
</script>
Here is the JSON file :
[{"_id":"5624711f1a530785d511e747","__v":0,"name":"Beverages","description":"Soft drinks, coffees, teas, beers, and ales","created":"2015-10-19T04:27:11.649Z"}]
Currently, It doesn't display any data. I have tried pure JS instead of jquery but it doesn't help.
This is what I got in the Chrome Console : GET localhost:3000/categories?callback=jQuery1113012827125121839345_1445236000644&_=‌​1445236000645 net::ERR_UNKNOWN_URL_SCHEME
Added http:// - does not make a difference

cross domain reading remote url using Jquery/Ajax/Json

I have an HTML page from which i want to read a remote webpage which is at http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113
The webpage returns a value depending on the Query string parameter passed that is the productID
My question is since its cross domain reading data which is the best method to use Jquery/Ajaz/Json or mix of all these ?
I have searched it on Google but i cant find example of reading and displaying the data in a DIV .
I am using this code but it doesnt display anything
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113', function(data){
$.each(data, function(i, tweet){
$('#tweets').append('<li>' + tweet.text + '</li>');
alert(tweet.text);
});
});
});
</script>
<ul id="tweets"></ul>
A basic example like this should help you get started:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "gulmarg",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 5 ) return false;
});
});
DEMO

How can I query the youtube api to return the yt$videoid?

I'm currently using this to query for the first video matching deadmau5:
https://gdata.youtube.com/feeds/api/videos?q=deadmau5&v=2&alt=json&max-results=1&prettyprint=true
This returns a bunch of info including the video id, and seems wasteful on both my end and there's. All I need is the youtube id, is there a more efficient way to return only the video id?
Try this it makes use of jquery so you may need to include jquery library before running it
$(function(){
var url = 'https://gdata.youtube.com/feeds/api/videos?q=deadmau5&v=2&alt=json&max-results=1&prettyprint=true';
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data){
var videoLength = $(data.feed.entry).length;
for(x=0; x<videoLength;x++)
{
var videoUrl = data.feed.entry[x].media$group.yt$videoid.$t;
console.log(videoUrl);
}
}
});
});
Check out console to see the video id. It can also work with a playlist and will provide all the video ids under a playlist
Found it. This is more or less what I was looking for because I'm parsing this within rails:
https://gdata.youtube.com/feeds/api/videos?q=deadmau5&v=2&alt=json&max-results=1&prettyprint=true&fields=entry(media:group(yt:videoid))
Note the difference is I added fields=entry(media:group(yt:videoid))
The above answer is great though and probably better in a bunch of situations

Using the Yahoo Weather API with JSON and the script tag

I'm trying to get the Yahoo Weather with JavaScript. I originally made a proxy, but found that clumsy.
So can get the JSON response from http://weather.yahooapis.com/forecastjson?w=9807, and I know that the script tag can avoid the same-domain restrictions, but I'm getting a syntax error.
Yahoo's JSON response isn't padded; I've got the callback working but the browser isn't interpreting the JSON properly.
I've seen many examples like How to read yahoo weather JSON data with Jquery ajax but it's so weird because all those give me the cross-domain error.
Can anyone help me with this? Cross domain, yahoo weather, without special servers or YQL or anything like that. Something that just works out of the box.
If you're expecting JSON-P then you need to add a callback function name to the query. With jQuery, this is always ?. jQuery will substitute it with a randomly generated function name:
var query = escape('select item from weather.forecast where location="CAXX0518"'),
url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=?";
$.getJSON(url, function(data) {
console.log( data );
});
If you want to use yql, this is the link:
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
When you call it just pass that as the parameter in your jquery. So, in other using STeve's code you can simply replace the url passed into the getJSON function call with the yql link and of course replace the zip code you want to use for the location. So, here's the code:
$(document).ready(DocReady);
function DocReady()
{
var Result = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D%2233015%22&format=json", "",
function (data)
{
$("body").append("Sunrise: " + data.query.results.channel.astronomy.sunrise + "<br />");
$("body").append("SuntSet: " + data.query.results.channel.astronomy.sunset + "<br />");
});
}
Here is the section you need to replace to get the proper location:
Enter zip code between both %22's
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D%22
33333
%22&format=json
Let me know if you have any questions.
Here is some code
$(document).ready(DocReady);
function DocReady()
{
jQuery.support.cors = true;
var Result = $.getJSON("http://weather.yahooapis.com/forecastjson?w=9807", "",
function (data)
{
$("body").append("Sunrise: " + data.astronomy.sunrise + "<br />");
$("body").append("SuntSet: " + data.astronomy.sunset + "<br />");
});
}