Why is data not received from node server to angular client? - angularjs

I've the following SETUP: AngularJS for UI, MongoDB for database and Node.js for server.
FUNCTIONALITY of my web page: It is tabular website and 3 tabs to enter details all of which is saved to Database and one tab called EDIT/DOWNLOAD to display specific details like 4-5 columns(fields) of each row(document) and further, for each document displayed there is an option to edit or download details.
WORK FLOW: on click of tab EDIT/DOWNLOAD a function [ say viewDatabaseDetails()] is called which in turns gets those details to be displayed as a table for each document in database.
On click of download button again that specific document detail goes to NODE and then calls the specific document and save it all according to a template text file and send that file for download to client and deletes that file.
On click of edit button, it again picks up data and populate those 3 tabs where user has to enter but here any changes made is updated in database instead of saving as a new document.
ISSUE: : When I click on function viewDatabaseDetails(), sometimes Angular displays data, sometimes it fails. Success of receiving data to display varies between 1-4 clicks on tab button to call viewDatabaseDetails(). Also, when I click on download button, sometimes files is received for download on the first click, sometimes after clicking on download button for 2-4 times file is received by client. I have checked node part on console, angular is sending all the details correctly every single time I click on download button or viewDatabaseDetails(), node is doing all the processing like data operations, creating file to send, creating proper response to send all the documents details but somehow it is not being received by angular.
What might be happening is either the data is lost in network or timeout happens before receiving data/file as only server to client communication has issue. I checked network console in IE [i've a restriction to use only IE] upon success time taken is greater than time taken upon failure.
EDIT:
Error explained according to below code: When I click on view button in UI, sometimes data is displayed correctly, sometimes I get error as SyntaxError: Invalid Character.
UI:
<button ng-click="viewDatabase()"> View </button>
Controller:
$scope.viewDatabase = function(){
$http.get('/getDatabase').success(function(response){
$scope.outputs = response;
}).error(function(){
console.log("error");
});
};
UI: for displaying response
<div>
<table>
<tr>
<td>Name </td>
<td>City </td>
<td>Country </td>
</tr>
<tr ng-repeat="output in outputs">
<td>{{output.Name}} </td>
<td>{{output.City}} </td>
<td>{{output.Country}} </td>
</tr>
</table>
</div>
Node and MongoDB code:
//other require statements
var mongoose = require('mongoose');
var db = mongoose.connect(ConnectionString:port);
var PropertyFileSchema = new Schema({
Name: String,
City: String,
Country: String
});
PropertyFile = db.model('PropertyFile', PropertyFileSchema');
http.createServer(function(req,res){
//putting only required part of code
if(req.url=="/getDatabase"){
res.writeHead(200,{'content-type': 'application/json'});
PropertyFile({},'Name City Country', function(err, docs){
console.log(docs); //always displays if anything in database
res.end(JSON.stringify(docs));
});
}
});

Related

Coldfusion - Refreshing Page When A Database Record Updates

Good day,
Let me describe my problem :
Scenario :
User 1 has a coldfusion webpage, containing 6 alerts as html elements populated using a database. User 1 is constantly monitoring this page for changes.
A user on a different computer (different session) logs into a admin console and add's a 7th element and inserts it into the database.
The database contains a field that changes from 0 to 1 as soon as an alert is added and inserted into the database.
The webpage of User 1 not has to dynamically refresh or update with the 8th alert.
Problem :
I am struggling to run a async loop that queries the database permanently for the record that tells it there is a change, while not freezing the rest of the page.
Solution :
I need to run a cfquery to check the isUpdated field in the database.
That cfquery needs to be run every minute.
As soon as the cfquery returns a 1, the page should refresh which in turn will populate the new alert as well.
Can be done through sockets, and you do not have to check the availability of a new record every minute.
You can also do it with javascript/jquery:
<script>
var lastAlert = '#lastAlert#'; //last at the time of loading the page
setInterval(function() {
lastAlert = isUpdated(lastAlert);
}, 60000);
function isUpdated(lastAlert){
res = lastAlert;
$.ajax({
url: 'checkAlerts.cfm', //in this file do check for changes in the database. should return the number of the last alert
type: 'POST',
data: {lastAlert:lastAlert},
cache: false,
success:function(res){
if(res > lastAlert){
//your code if there is a new entry
alert('a new entry has been added');
}
}
});
return res;
}
</script>
I did not check the code! But I hope you understand how to proceed.

how to get infinite scroll with remote data with angularjs

Currently i am developing a listings portal here i am using angularjs as frontend and through this i am calling api to load data right now when a user hit all listings link whole data is loading and showing at this point the data is very less so problem but if data is large it will take some loading time, my requirement is when a user first click the link it has to show only top 50 listings and if user scrolls down the page then again api has to call for next 50 listings and so on how can i achieve this with angularjs.
Hope this helps.
$scope.limit=50;
$scope.loadMore1=true;
$scope.count=0;
$scope.loadMore=function()
{
$scope.limit=$scope.limit+100;
if($scope.limit>=$scope.count) {
$scope.loadMore1=false;
} else {
$scope.loadMore1=true;
}
$("html, body").animate({ scrollTop: $(document).height() }, 1000);
}
Inside your ajax call or api call
if(result.data.items.length<=50)
{
$scope.loadMore1=false;
} else {
$scope.count=result.data.items.length;
$scope.loadMore1=true;
}
And finally HTML list which loads certain number of results
<li ng-repeat="r in results | limitTo:limit"></li>
<button class="loadMore" ng-show="loadMore1" ng-click="loadMore()">Load more Items...</button>

How to get different data in ng-repeat ? - AngularJS

I'm using AngularJS and I have created an web app.
I don't know how to get values from one specific link.
I have an admin page where I have all users and I get them using ng-repeat
<div ng-repeat="user in allusers">
But I have created routes for example user level and I have added them to http://mylink.com/user_level/john#doe.com -- (that's example so I will get user level via user email)
The recommended approach would be to have the service that retrieves the users, send the user's level in the user object itself.
But, if this is not an option and you have to make separate service calls to get the user's level, this is how you would do this.
function getUserLevels(users) {
for(var i=0; i<users.length; i++) {
getUserLevelForUser(users[i]);
}
}
function getUserLevelForUser(user) {
$http.get(BASE_URL + '/' + user.email)
.then(function (response) {
user.userLevel = response.data.userLevel;
});
}
getUserLevels($scope.users);
Since I do not have access to your API, I've created a plunker app that invokes the Open Movie Database API. In this demo, instead of the user's level, I will be fetching a movie's director. Also, instead of using the user's email in the url, I will be using the movie name.
See working plunker here

$scope not updating after passing to new view with $location.path

I have a simple CRUD I put together with Angularjs. From a product list display I pass the user to a new view template for the "Create New" form.
The form processes fine and updates the database. I then pass the user back to the list display using "$location.path(url)".
For some reason when the list page displays, the changes do not appear in the $scope and you have to refresh the page to see the changes.
Sample code:
$scope.acns = acnFactory.query()
.$promise.then(function (data) {
$scope.acns = data;
});
the above displays the list of items.
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
The above POSTs the new product then redirects to the list page (/acn)
My assumption is that the list page will reprocess or watch the changes to the $scope but the view does not update.
The problem is most probably here:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
creating a product most certainly consists in sending an HTTP request to the server. This is asynchronous. This means that acnFactory.create() returns immediately after the request has been sent. Not after the response has been received.
So, this code sends the request to create the product and immediately goes to the page which lists the products. The GET request sent to get the product list is thus sent almost at the same instant as the one used to create the new product. The two requests are handled concurrently by the server, and the returned list contains the list without the new product, which is being created in a separate transaction.
You need to wait for the response to come back, and make sure it's successful, before going to the product list. Assuming the service returns a promise, as it should do:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn).then(function() {
$location.path('/acn');
});
};

Query a database with drupal 7

I have searched the internet for a way to use our history database on our drupal 7 site. I have a database built with names, marriage dates, etc. I would like to have a basic page to do a search. I found a site that helped with the code, but it is not working. I am not a programmer, but I can follow directions. Here is the code I have:
On a basic page using php code as my input format,
<html>
<body>
<script language=”javascript” type=”text/javascript”>
<!–
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try{
ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e){
// Something went wrong
alert(“Your browser broke!”);
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var lastphp = document.getElementById("lastphp").value;
var queryString = “?lastphp=” + lastphp;
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
ajaxRequest.send(null);
}
//–>
</script>
<form name="myForm">
<table border=”0″>
<tr>
<td width = 100>Last Name: <br /></td>
<td><input type="text" id="lastphp"> </td>
</tr>
</table>
<br />
<input type="button" onclick="ajaxFunction()" value="Search" />
</form>
<div id="ajaxDiv"></div>
</body>
</html>
Then, I created a php file:
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","root","") or die('Cannot connect to the database because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db(“genealogy”) or die(“Unable to select database”); //select which database we’re using
// Retrieve data from Query String
$last = $_GET['lastphp'];
// Escape User Input to help prevent SQL Injection
$last = mysql_real_escape_string($last);
//Build and run a SQL Query on our MySQL tutorial
$query = “SELECT * from columbus_ledger_enquirer_obituary_db”; //just grab every row from our table
$results = mysql_query($query)or die(mysql_error());
//print what the user entered (eventually I’m sure you’ll want to use this data in your query)
echo “You Entered: ” . $last . “<br><br>”;
//print the results
echo “Database Results: <br>”;
while($row = mysql_fetch_array($results)){
echo “$row[lastname]<br>”; //NOTE: Here we are printing all the data from the ‘lastname’ column of our database, either change this name, or make sure you have a lastname column with some data in it
}
?>
I placed the php file in a folder called php under /sites/default.
The basic page has a nice box and search button, but when I type in a name, nothing happens.
Can anyone here tell me what's wrong?
Thanks
As #SpaceBeers mentions this is really not a good way to do this kind of thing in Drupal (Google "bootstrapping Drupal" or "access custom database in Drupal" for some ideas).
The reason your code probably isn't working, though, is because you're calling your AJAX in using the following code:
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
The problem is in the path...you mention you've put your "php" folder in '/sites/all', so surely the path from your AJAX call needs to be the same:
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);
These days "there is a module for it" (to query external databases in formats such as Oracle, MS SQL, Postgress, SQLite, or just any PDO compliant format). It's the Forena module (disclosure: I'm a co-maintainer of it).
Head over to its demo site to see it as work, and refer to its community docu for way more details. Here is a quote from its docu:
... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Resources