Trouble getting data from Firebase database Node.js/JavaScript - javascript

Good morning everyone I'm having a little trouble with Firebase as a new user. In my previous question I asked how I could use my express server making API calls to pass that data retrieved into my firebase database and I was able to make it work! However, now I want to take that data from my database and use it to populate my DOM on the client side.
So we're clear this is how the work flow got my app goes:
Make an AJAX request from my client to my express app app.jssending a small data object {search: search} where the value for search is captured in a form on the client. (works)
Take that data object and make another AJAX request to the third party API, which returns another data object. (works)
Take that response object from the third party API and send that to my database. (works)
A script client-side pulls information from my database to populate the DOM. (not working)
Looking at the myriad of tutorials is tough and I'm following the guides I find exactly using some fine copy pasta, but I'm still stuck.
Here is the client side script firebaseData.js that I'm using to retrieve data from my database, I'm trying to get all the data at the endpoint [my database url]/user:
$(document).ready(function() {
// create object instance of my Firebase database
var myDBReference = new Firebase([my database url]);
console.log(myDBReference.child("user"))
});
And it returns this in the console client-side:
X {k: Ji, path: P, n: Ce, pc: false, then: undefined…}
And that's all I've been able to get so far. Below is my index.html where I link to firebase it's cdn and a bunch of other stuff I was just told to include in my project:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="top">
<h1>Just Trying to Make a Halo App</h1>
<form id="searchForm">
<input id="searchField" type="text"></input>
<input id="searchButton" type="submit" value="search"></input>
</form>
</div>
<div id="imageContainer">
<img id="emblem">
<img id="spartan">
</div>
<div id="dataContainer">
<h2></h2>
<p></p>
</div>
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "[my key value]",
authDomain: "[authDomain value]",
databaseURL: "[databaseURL value]",
storageBucket: "[storageBucket value",
};
firebase.initializeApp(config);
</script>
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="request.js"></script>
<script type="text/javascript" src="firebaseData.js"></script>
</body>
</html>
In actuality the var config object has all the correct information generated from the firebase console- I wish that's all I would need to fix this! Please let me know if you require any more information I'd be happy to provide it and thanks for taking the time to check out my question.
Happy Saturday!

myDBReference.child("user") is just the reference to where the data is stored. To actually retrieve the data you will need to work with .on() or .once(). I strongly recommend you to take some time reading firebase documentation for retrieving data.
firebase.database().ref().child("user").once('value', function(snapshot) {
if(snapshot.value()){
//logs everything that is under /user
console.log(snapshot.value());
}
});
Keep in mind that if you have many users under /root/user, after retrieving the whole branch you will need to iterate over them with:
snapshot.forEach(function(childSnap){
console.log(childSnap.val());
});
Update:
Since I see you are not working with any SPA framework such as Angular (with angularfire), if you want to display the data that you are retrieving from firebase you will need to work setting an element id and than call document.getElementById() inside your callback to manipulate it.
<p id="username"></p>
document.getElementById("username").value = snapshot.val();

Related

How to $.post a js variable and store it to php for later use,similarly to LocalStorage?

In local storage,we store for example localStorage.setItem("test",$('#testinput').val());
And 2 years later,as long we have'nt cleared our browser's local storage we just ask for the key in LS and we get it back like this $('#testinput').val(localStorage.getItem("test"));
Now let's say (because LS is available only within one system and one browser) I want to store this particular data to a server-side PHP file, and have it available there to be accessed whenever I want, what would be the simplest and most common practice to do that based on my example and my snippet below*?
Should I store it in a PHP cookie?
Note that I have some familiarity with $.post and $.get with jquery, and concerning PHP I know as much as getting the request and send a response back, I just started learning.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function storeVALUE() {
localStorage.setItem("test", $('#testinput').val());
}
function retrieveVALUE() {
$('#testinput').val(localStorage.getItem("test"));
}
</script>
</head>
<body>
<button onclick="storeVALUE()">STORE VALUE</button><button onclick="retrieveVALUE()">RETRIEVE VALUE</button>
<input id="testinput">
</body>
</html>
*SO snippets do not access LS, but you get the idea
if this is necessary with your code , you can store variable value using cookies in json format and later use it using $_COOKIE[$cookie_name]

Understanding forerunner to-do tutorial?

I am looking at the Forerunner to-do tutorial (http://www.forerunnerdb.com/tutorial/todoList.html) and am having difficulties duplicating its results. I understand the tutorial might be running on Node, and thus dependencies such as jsviews and jquery might not necessarily show up on the index sample page. However, there are problem areas that I do not understand. For instance, this section:
<!-- Create a DB instance and store it globally -->
<script type="application/javascript">
window.fdb = new ForerunnerDB();
db = fdb.db('test');
// Ask forerunner to load any persistent data previously
// saved for this collection
db.collection('todo').load();
</script>
Leads to errors, where fdb is not a function and db is not defined. I make sure to place this JavaScript code after the dependencies are loaded in, namely fdb-all.min.js, but I still get errors.
At the moment I am replicating the code on the finished products section, but adding the jsviews and jquery dependencies with the main fdb-all.min.js. Thus, my code looks the same as the example in the tutorial, yet doesn't run.
I am also running this in a non-HTTP environment, which should not be a problem because I have a separate example that works while running on my Desktop.
EDIT:
If it helps, this is my code verbatim.
<html>
<head>
<title>My First ForerunnerDB Todo App</title>
</head>
<body>
<!-- Include the whole forerunner system, bells, whistles and kitchen sink -->
<script src='http://www.forerunnerdb.com/js/forerunnerdb/dist/fdb-all.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://www.jsviews.com/download/jsviews.min.js'></script>
<script src='http://www.forerunnerdb.com/js/forerunnerdb/dist/fdb-autobind.min.js'></script>
<!-- Create a DB instance and store it globally -->
<script type="application/javascript">
window.fdb = new ForerunnerDB();
db = fdb.db('test');
// Ask forerunner to load any persistent data previously
// saved for this collection
db.collection('todo').load();
</script>
<!-- Define a todo item template -->
<script type="text/x-jsrender" id="todoItem">
<li data-link="id{:_id}">
<span>{^{:text}}</span>
</li>
</script>
<!-- Create an element where our todo items will be output -->
<ul id="todoList"></ul>
<!-- Create our item entry form -->
<form id="todoForm">
<input id="todoText" type="text" placeholder="Enter todo item" />
<input type="submit" value="Add Item" />
</form>
<!-- Use jQuery to hook the onsubmit of our form -->
<script type="application/javascript">
$('#todoForm').on('submit', function (e) {
e.preventDefault();
// Get the form's todo item text
var itemText = $('#todoText').val();
// Add the new item to ForerunnerDB's todo collection
db.collection('todo').insert({
text: itemText
});
// Now we've added the item to the collection, tell
// forerunner to persist the data
db.collection('todo').save();
});
$('body').on('click', '#todoList li', function () {
// Get the item id for the todo item clicked on
db.collection('todo').remove({_id: $(this).attr('id')});
db.collection('todo').save();
});
</script>
<!-- Finally we tell forerunner to data-bind the collection to the todo list -->
<script type="application/javascript">
db.collection('todo').link('#todoList', '#todoItem');
</script>
</body>
</html>
I tried your code, and the problem is you're including the scripts from a remote server (that's not a cdn). Downloading the Forerunner scripts and including them locally made everything work.

API Management Portal Azure Template Restriction

I am calling an api and getting some values in json format now I want to restrict some user on client side based on the response I get from the api. for example if user is a guest then it haven't show the subscribe button otherwise it have. In developer portal we use DotLiquid view engine. Now i have one question how can i use this in dotliquid. here is my code where i use Jquery to get data and javascript to restrict the user on client side
Code
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
var root = 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false';
$(document).ready(function () {
var showData1;
$('#get-data').click(function () {
var showData;
jQuery.ajax({
url: "https://httpbin.org/get",
dataType:'json',
success:function(response)
{
$('#a').html(response.origin );
$('#b').html(response.url );
if(response.url=="https://httpbin.org/get"){
$("#a").fadeOut(1000);
}
}
});
showData.text('Loading the JSON file.');
});
});
</script>
<!DOCTYPE html>
Get JSON data
<div id="show-data"></div>
<p id="a"></p>
<p id="b"></p>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I can't quite tell from your source code, but in the DotLiquid templates we use on the developer portal the template variables are fixed currently. Please add your feature request to have user variables in each template to our feedback portal http://aka.ms/apimwish

Push Notification Custom Save Browser id in Database

hi i am newbie to php and javascript and i am working on a project of Push Notification for my website which will push a notification to the user when a news related to specific category is published on my website i am using following code and curl with the help of google documentation
<html>
<head>
<title>Push Notification codelab</title>
<link rel="manifest" href="manifest.json">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<h1>Push Notification codelab</h1>
<p>This page must be accessed using HTTPS or via localhost.</p>
<script src="js/main.js"></script>
<button id="send">Send</button>
<script>
$("#send").click(function() {
$.get("curl.php", function(data) {
console.log(data);
});
});
</script>
</body>
</html>
now i am wondering how to store a user's browser id or something so that it can send a notification to specific browser for specific category news.i am really looking forward to you guys to help me out for this problem.
there is nothing so-called as browser id, but you can generate a unique and store that in the _COOKIE, best combination of creating an unique id would be MD5(USER_AGENT . SALTMIX_STR . IPADDR), this combination will generate a unique id for each browser and you can store that in cookie using PHP eg. $_COOKIE["BROWSER_KEY"] = 'YOUR_UNIQUE_KEY'
EXAMPLE
<?php
$generateUniqueKey = md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR']."!##zYp04)+");
$_COOKIE["BROWSER_KEY"] = $generateUniqueKey; //Sets a key
echo $_COOKIE["BROWSER_KEY"]; //retrieves the set key
?>

Cloudinary + Sails.js direct upload doesn't work

i'm trying to make cloudinary direct upload working but something in the documentation is missing... here are the steps i'm doing:
Controller:
/**
* MyaccountController
*
* #description :: Server-side logic for managing myaccounts
* #help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'MyCloudName',
api_key: 'MyAPIKey',
api_secret: 'MyAPISecret'
});
Now this is my layout:
<!--SCRIPTS-->
<script type="text/javascript" src="/js/dependencies/sails.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
<script type="text/javascript">
cloudinary.cloudinary_js_config();
var cloudinary_cors = "http://" + window.location.host + "/cloudinary_cors.html";
console.log(cloudinary_cors);
cloudinary.uploader.image_upload_tag('photo', { callback: cloudinary_cors });
$(".photo").cloudinary_fileupload();
// Using the config function
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
</script>
My form:
<form action="" method="post" enctype="multipart/form-data" class="upload_form">
<div class="form-group">
<label>Foto de perfil</label>
<input type="file" name="photo" id="photo" class="photo">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Cargar</button>
</div>
</form>
I don't get why it isn't working, in the docs it says Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters to be available. Note: never expose your api_secret in public client side code.
To automatically set-up Cloudinary's configuration, include the following line in your view or layout:
cloudinary.cloudinary_js_config()
This is done...
Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.
This solution requires placing cloudinary_cors.html in the static folder of your Node application. This file is available in the html folder of Cloudinary's Javascript library. The following code builds a URL of the local cloudinary_cors.html file:
Done...
Direct upload file tag
Embed a file input tag in your HTML pages using the image_upload_tag view helper method.
The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.
cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors });
this is what i don't get... this is the uploader? how should i use it? and then i don't know what else to do, i'm using different docs to make it work but nothing helps... I hope anyone who did this can help me, thanks!
On controller initialize cloudinary as
var uploader = cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors, html: { multiple: 1 } });
and pass it to view and render it over there,
<%-uploader%>
then use jquery to get data:
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {}
you can use this script to bind the data to some hidden fields inside your form and
cloudinary-fileupload will be generated when <%-uploader%> is rendered
In addition to CodeBean's answer, note that it seems that there are different ways of using Cloudinary that are mixed here (in the original code as was in question).
Controller
As far as it can be seen from here, the MyaccountController controller doesn't do a thing:
You're requiring "cloudinary" - presumably from npm install, which creates an instance of the jQueryless Cloudinary class.
The variable is local to the controller so has no effect on the rest of the code
View:
Only one of these lines is required (preferably the second one):
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
This method returns a string with the <script> tag. The string should be then embedded in the HTML code. It is a server side code.
Here, it does nothing.
cloudinary.cloudinary_js_config();
If you're using the jQuery File Upload code, you should refer to $.cloudinary. cloudinary was never defined in your layout.
Now you're creating a jQueryless instance, which you don't use afterwards.
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
Finally, there's an open-ended comment with the code you were supposed to use in the beginning of the whole script:
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
Regardless of CodeBean's response, you still need to config $.cloudinary.

Categories

Resources