Javascript contacts not showing - javascript

I am trying to develop a simple application access all the contacts using phonegap. But every time i try to run the code , onError() function is getting called instead of onSuccess().
Here is the code :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
var options = new ContactFindOptions();
options.filter = "";
options.multiple=true;
var fields = ["displayName"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
var names=[];
function onSuccess(contacts)
{
for (var i = 0; i < contacts.length; i++)
{
names.push("Display Name = " + contacts[i].displayName);
}
alert(names);
}
function onError(contactError)
{
alert('error !!');
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>
<div data-role="content">
<p>
Hello Phonegap!!
</p>
</div>
<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>
</body>
</html>

<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter="";
options.filter="";
options.multiple=true;
var fields = ["*"]; //"*" will return all contact fields
navigator.contacts.find(fields, onSuccess, onError, options);
}
// display the address information for all contacts
function onSuccess(contacts) {
//console.log(JSON.stringify(contacts))
var li = '<ol data-inset="true" data-role="listview">';
$.each(contacts, function(key, value) {
if(value.name){
$.each(value.name, function(key, value) {
if(key == 'formatted'){
name = value;
}
});
}
if(value.phoneNumbers){
$.each(value.phoneNumbers, function(key, value) {
phone = value.value;
});
}
li += '<li style="text-decoration:none;">'+name+' '+phone+'</li>';
});
li += '</ol>';
$("#contact").html(li).trigger('create');
$("#contact").listview("refresh");
};
function onError(contactError) {
alert('onError!');
};
</script>

Related

Using Timber Framework counter with a URL API that continuously counts up

My skills with jquery and such are limited when it comes to this. For our website we are using timber framework with some of the plugins. I would like to use their counter but have the counter go up in real time. Please help if you can. Thank you in advance. in the HTML i have wrote realtime where i would like the counter to be realtime. I hope i have provided enough information. So in summary what i need help with is i would like to use the timber framework style and look but have the counter be realtime instead of stopping at a number and being a very basic counter.
HTML
`
<div class="column width-4 offset-4 center">
<div class="counter-wrapper">
<p style="font-size:60px;" class="counter lead"><span class="stats-1" data-count-from="1300000" data-count-to="realtime" >1000000</span></p>
<p style="font-size:36px;" class="lead">Hotspots</p>
</div>
</div>
`
Javascript
<script>
$( document ).ready( function(){
$( '.stats-1' ).counter();
$( '.stats-2' ).counter({
autoStart: true
});
});
</script>
Realtime counter URL
https://reelsonar-services.com/api/v1/hotspot_count
OUR COUNTER from a sample site
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.flipcountdown.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.flipcountdown.css" />
<script>
var hotspot_count = 1000000;
function fetch_waterbody_count() {
var url="https://reelsonar-services.com/api/v1/hotspot_count";
//var url="http://reelsonar-services.com:8085/hotspot_count";
var html = [];
$.getJSON( url, function( data ) {
console.log( data );
$.each(data, function(index, d){
html.push("Hotspots: ", d.hotspot_count, "<br>");
var count = parseInt( d.hotspot_count );
if( count != hotspot_count) {
hotspot_count = count;
update_counter( hotspot_count )
}
});
});
}
function update_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function reset_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function pulse_hotspot() {
(function pulse(back) {
$('#hotspot_img').animate(
{
'font-size': (back) ? '25px' : '35px',
opacity: (back) ? 1 : 0.5
}, 1200, function(){pulse(!back)});
$('#hotspot_img img').animate(
{
'width': (back) ? '125px' : '112px'
}, 1200);
})(false);
}
</script>
<body style="background: lightblue;text-align: center">
<script>
$(document).ready(function(){
$("#fetchButton").click(function(event){
fetch_waterbody_count();
});
$("#addOneButton").click(function(event){
hotspot_count += 1;
update_counter( hotspot_count );
});
$("#addTenButton").click(function(event){
hotspot_count += 10;
update_counter( hotspot_count );
});
$("#resetButton").click(function(event){
reset_counter(1000000);
});
setInterval(fetch_waterbody_count, 2000);
pulse_hotspot();
});
</script>
<script>
jQuery(function(){
jQuery('#flipcountdown').flipcountdown({size:'md',tick:hotspot_count}); <!-- Medium sized -->
})
</script>
<div style="font-size: x-large; padding-bottom: 1em">ReelSonar Global Hotspot Counter</div>
<div style="font-size: large; padding-bottom: 1em">Displays Hotspots as they are created by our users in real time.</div>
<pre>(Retrieves Hotspot count every two seconds)</pre>
<div id="hotspot_img"><img src="hotspot.png" /></div>
</body>
</html>
This is a polling issue: send Ajax request periodically, get the latest number and display it on screen (using Timber's counter to add animation effect).
Here is a working example. Please note it is a bit complex because the returned data is an array, not a single object (need to handle the situation when multiple numbers are returned in one array):
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="lib/css/components/timber.css" />
</head>
<body>
<span data-count-from="1" data-count-to="1" id="counter"></span>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="lib/js/plugins/jquery.tm.counter.js"></script>
<script type="text/javascript">
$(function() {
var queue = [];
var url="https://reelsonar-services.com/api/v1/hotspot_count";
var counter = document.getElementById('counter');
var $counter = $(counter);
var latestNum = null;
getData(true);
setInterval(function() {
getData();
}, 30000);
function getData(init) {
$.getJSON(url, function(data) {
if (init) {
var num = data.shift().hotspot_count;
counter.dataset.countFrom = num;
$counter.text(formatNumber(num));
}
queue = queue.concat(data);
playCount();
});
}
function playCount() {
if (queue.length === 0) {
return;
}
var countTo = queue.shift().hotspot_count;
if (countTo && countTo === latestNum) {
playCount();
}
latestNum = countTo;
counter.dataset.countTo = countTo;
$counter.counter();
setTimeout(function() {
counter.dataset.countFrom = countTo;
if (queue.length > 0) {
playCount();
}
}, 1000);
}
function formatNumber( number ) {
return number.toString().replace( /(\d)(?=(\d{3})+$)/g, '$1,' );
}
});
</script>
</body>
</html>

Library.add is not a function error

I am trying to execute this code:
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
Library.add(listItem);
console.log(Library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
The HTML is here:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
What I'm trying to do is press the addButton and the onclick will run the addBook function under the libraryUI object. The title of the book, in an input field, will then be used to create an object with the title of the book in it. I want to add that book to a list of books (an array) in an instance of Library. When I try to do so with the following code, I get the error "Uncaught TypeError: Library.add is not a function". I thought that Library.add is a function.
I added:
var library = new Library();
because I thought I had forgotten to create an iteration of Library, but I still came up with the exact same error. Please help. :)
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function(book) {
this.books.push(book);
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
library.add(listItem);
console.log(library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
Shouldn't it be library.add instead of Library.add?
Also: why:
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
instead of:
Library.prototype.add = function(book) {
this.books.push(book);
}
?
If I change Library.add to library.add and console.log(library.books) I think this does what you want.

Handelbars.js: rendered HTML code not displayed

I new to Handelbars.js and I wanted to test it out. I just have one html file, whose content I want to be rendered by handlebars.js:
HTML file:
<html>
<head>
<script type="text/javascript">
console.log("Head:getting css");
</script>
<link rel="stylesheet" type="text/css" href="css/main_2.css">
</head>
<body>
<div class="phone-screen">
<script type="text/javascript">
console.log("Body:start MasterPage");
</script>
<!--MasterPage -->
<script id="app-bar" type="text/x-handlebars-template">
<div class="app-bar-container">
</div>
<div class="nav-bar-container">
<div class="nav-tab-left nav-tab-selected nav-tab-label-Selected">
<div class="tab-lable-centered ">History</div>
</div>
<div class="nav-tab-right nav-tab-notSelected ">
<div class="tab-lable-centered ">New</div>
</div>
</div>
</script
<!-- Content -->
<script id="workout-list-tpl" type="text/x-handlebars-template">
<div class="list-container">
<div class="week-seperator">
<div class="week-lable-right ">Week 12</div>
</div>
<div class="workout-card-white">
<div class="workout-card-label ">Workout</div>
</div>
</script>
<script type="text/javascript">
console.log("Body:getting Scripts________________________");
</script>
<script src="lib/handlebars.js"></script>
<script src="js/storage/memory-store.js"></script>
<script src="lib/jquery-1.8.2.min.js"></script>
<script src="js/MainView.js"></script>
<!--<script src="js/EmployeeView.js"></script>-->
<script src="js/main_2.js"></script>
</div>
</body>
The app javascript:
var app = {
initialize: function() {
console.log("initializer start: ");
var self = this;
//this.detailsURL = /^#employees\/(\d{1,})/;
//this.registerEvents();
this.store = new MemoryStore(function() {
self.route();
});
},
route: function() {
console.log("route function start.");
var self = this;
var hash = window.location.hash;
if (!hash) {
if (this.homePage) {
//this.slidePage(this.homePage);
} else {
console.log("homePage: ");
this.homePage = new MainView(this.store).render();
console.log("homePage = " + this.homePage );
//this.slidePage(this.homePage);
}
return;
}
var match = hash.match(this.detailsURL);
if (match) {
//this.store.findById(Number(match[1]), function(employee) {
//self.slidePage(new EmployeeView(employee).render());
//});
}
},
showAlert: function (message, title) {
if (navigator.notification) {
navigator.notification.alert(message, null, title, 'OK');
} else {
alert(title ? (title + ": " + message) : message);
}
},
};
console.log("app.initialize();");
app.initialize();
And the view.js:
var MainView = function(store) {
this.render = function() {
console.log("render function execution:" + MainView.template() );
this.el.html(MainView.template());
return this;
};
this.initialize = function() {
console.log("MainView init start.");
// Define a div wrapper for the view. The div wrapper is used to attach events.
this.el = $('<div/>');
//this.el.on('keyup', '.search-key', this.findByName);
};
this.initialize();
}
console.log("Handlebars.compile($(app-bar).html()); " );
MainView.template = Handlebars.compile($("#app-bar").html());
console log:
Head:getting css main_2.html:4
Body:start MasterPage main_2.html:12
Body:getting Scripts________________________ main_2.html:41
Handlebars.compile($(app-bar).html()); MainView.js:19
app.initialize(); main_2.js:46
initializer start: main_2.js:5
route function start. main_2.js:15
homePage: main_2.js:22
MainView init start. MainView.js:10
render function execution:
<div class="app-bar-container">
</div>
<div class="nav-bar-container">
<div class="nav-tab-left nav-tab-selected nav-tab-label-Selected">
<div class="tab-lable-centered ">History</div>
</div>
<div class="nav-tab-right nav-tab-notSelected ">
<div class="tab-lable-centered ">New</div>
</div>
</div>
MainView.js:4
homePage = [object Object]
The code goes through to the render function in view.js getting the html code but I do not know what happens next and hence why it is not rendered in the browser.
It seems I forgot the last step to append the generated html string to the html page:
$('body').append(page.el);

PhoneGap Script reads contacts correctly until I include photos (avatars)

Following script is supposed to return a list of contacts together with their emails, phone numbers and avatars (photos).
It works like a charm it I remove the avatar (photo) retrieval code, the moment I add it back. The script breaks. Does anyone have any experiences trying to display contact photos via phonegap?
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// specify contact search criteria
var options = new ContactFindOptions();
options.filter=""; // empty search string returns all contacts
options.multiple=true; // return multiple results
filter = ["displayName", "name", "phoneNumbers"];
// find contacts
navigator.contacts.find(filter, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
console.log(contacts.length);
for (var i=0; i<contacts.length; i++) {
var LI=$("#list").append('<li>'+contacts[i].displayName+'</li>');
if (contacts[i].phoneNumbers) {
for (var j=0; j<contacts[i].phoneNumbers.length; j++) {
$(LI).append('<span>'+contacts[i].phoneNumbers[j].value+'</span><Br/>');
}
}
if (contacts[i].emails) {
for (var j=0; j<contacts[i].emails.length; j++) {
$(LI).append('<span>'+contacts[i].emails[j].value+'</span><br/>');
}
}
if (contacts[i].photos) {
for (var j=0; j<contacts[i].photos.length; j++) {
alert(contacts[i].photos[j].value);
//$(LI).append('<span>'+contacts[i].photos[j].value+'</span><br/>');
}
}
/*if (contacts[i].photos) {
for (var j=0; j<contacts[i].photos.length; j++) {
$(LI).append('<img src="'+contacts[i].photos[j].value+'"/><br/>');
}
}*/
}
};
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
</script>
</head>
<body>
<h1>Example</h1>
<p>All Contacts in a list</p>
<ul id="list">
</ul>
</body>
Your filter does not included the "photos" field. Without it being specified the array of photos will not be populated.

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources