I am creating a phonegap app to fetch contacts and save them in the database. I have created two empty global arrays at the top that will save the phone number and display name of a person which will be later stored in a database table. To check that the contacts are successfully saved in the array, I have created a test_data() function.
Now my problem is that the test_data() code is not working and no values are displayed in the log. Now if I move that code from test_data() function to onSuccess() it works fine. Here is the code. Isn't it the proper way to declare global a array in JS.
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
var gcont = []; var gphon = [];
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var fields = ["displayName", "phoneNumbers"];
navigator.contacts.find(fields, onSuccess, onError, options);
test_data();
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for(var index=0;index<contacts.length;index++){
gcont[index] = contacts[index].displayName;
gphon[index] = contacts[index].phoneNumbers[0].value;
}
}
function test_data(){
for (z=0;z<gcont.length;z++){
console.log(gcont[z]);}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('Error With Contacts!');
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Find Contacts</p>
</body>
</html>
The call to test_data() doesn't work in onDeviceReady() because the onSuccess callback to contacts.find is asynchronous and the arrays have not been populated when test_data() is executed.
Related
I am trying connect my button in my html to my javascript file. I have been using this method for weeks and all of a sudden it stopped working and now I am receiving an error, "will_be_set_after_endpoints_apis_loaded is not defined at HTMLInputElement.onclick" and when I changed it to a function call like "greetByName();" it says method not defined which makes me think that the javascript file isn't being recognized. I will share snippets of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>FLINDER</title>
<meta charset="UTF-8">
<script src="hello.js"></script>
<!-- Load the Google APIs Javascript client library -->
<!-- Then call the init function, which is defined in hello.js -->
<script src="https://apis.google.com/js/client.js?onload=init">
</script>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<P><input id="input_greet_name" type="button" value="Please wait..."
onclick="will_be_set_after_endpoints_apis_loaded"></P>
JS File:
package com.google.training.helloworld;
//<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
function init() {
// You need to pass the root path when you load your API
// otherwise calls to execute the API run into a problem
// rootpath will evaulate to either of these, depending on where the
app is running:
// //localhost:8080/_ah/api
// //your-app-id/_ah/api
var rootpath = "//" + window.location.host + "/_ah/api";
// Load the helloworldendpoints API
// If loading completes successfully, call loadCallback function
gapi.client.load('helloworldendpoints', 'v1', loadCallback, rootpath);
}
/*
* When helloworldendpoints API has loaded, this callback is called.
*
* We need to wait until the helloworldendpoints API has loaded to
* enable the actions for the buttons in index.html,
* because the buttons call functions in the helloworldendpoints API */
function loadCallback () {
// Enable the button actions
enableButtons ();
}
function enableButtons () {
// Set the onclick action for the first button
//btn = document.getElementById("input_greet_generically");
//btn.onclick= function(){greetGenerically();};
// Update the button label now that the button is active
//btn.value="Submit";
// Set the onclick action for the second button
btn = document.getElementById("input_greet_name");
btn.onclick= function(){greetByName();};
// Update the button label now that the button is active
btn.value="Submit";
}
function greetByName () {
var loc;
var sal;
var schoolTypes;
var request;
loc = document.getElementById("loc").value;
sal = document.getElementById("sal").value;
var temp = loc;
schoolTypes = document.getElementById("schoolTypes").value;
var temps = schoolTypes;
if(loc == "" || sal == "" || schoolTypes == "")
{
alert("Please enter all valid options");
request = gapi.client.helloworldendpoints.sayHello();
}
}
The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'clapton'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.
I'm trying to build a basic JQuery app which loads images from Flickr, adds them to an array of jQuery objects, sequentially adds them to the DOM, fades them in, and fades them out in a 3 second cycle. However, in my displayImage function, I cannot use .hide(), .fadeIn() or .fadeOut() because it throws an 'Uncaught TypeError: Cannot read property 'fadeIn' of undefined' error. Here is my code, both the JS and the HTML:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
//Creates the empty array of jQuery image objects
var images = [];
$.getJSON(url, function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
//Populates the images array with jQuery objects defined from the Flickr JSON request
images.push($img);
// $("main .photos").append($img);
// $img.fadeIn();
});
});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
//Function which recursively calls 'displayImage' every three seconds
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
And
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flickr App</title>
<link rel="stylesheet" type="text/css" href="stylesheets/styles.css">
</head>
<body>
<header>
</header>
<main>
<div class = "photos">
</div>
</main>
<footer>
</footer>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/app.js"></script>
</body>
Any ideas what might be undefined? Note that the var $img = $("<img>").hide(); line in the $.getJSONrequest doesn't throw the undefined error!
Thanks very much!
EDIT:
I've also tried to make a synchronous request to fetch the JSON, to make sure it's loaded before the displayImage function is called, and still it throws the same errors:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
var images = [];
//THIS IS WHAT HAS CHANGED
$.ajax({url: url,
dataType: 'json',
async: false,
success: function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
images.push($img);
});
}});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
You need to wait for the JSON to return before you try to displayImage(0). The JSON request is asynchronous, so your call to displayImage is happening before any JSON has been returned.
I recommend stepping through with a Javascript debugger to better understand what’s going on. You would see then that images is empty, and therefore $displayedImg is undefined.
I'm building a phone app with Phonegap well, actually with Steroids.js which is built on top of Phonegap. Right now, all I want to do is retrieve the list of contact names and numbers from my phone upon the launching of my app. I took a look at the Contacts api here and I thought I was using it correctly. Below is the script I have inside of my head tags. What have I done wrong?
<script src="http://localhost/cordova.js"></script>
<script src="components/steroids-js/steroids.js"></script>
<script src="javascripts/application.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
function onSuccess(contacts) {
alert('ons');
for (var i = 0; i < contacts.length; i++) {
//trying to display contacts in an alert message when I launch my app
alert("Display Name = " + contacts[i].displayName);
}
}
// onError: Failed to get the contacts
function onError(contactError) {
alert('onError!');
}
</script>
In your above code your cordova.js file is misplaced somewhere.
like
<script src="http://localhost/cordova.js"></script>
You need to copy that cordova.js file into assest/www/ folder (like assest/www/cordova.js)
so it becomes like below in your html file
<script src="cordova.js"></script>
The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();
Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {
You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>