how to create contact in iphone using phonegap - javascript

I am new to iPhone development and phonegap also. Now i want to create contact in iPhone using phonegap. I got the link to create contact in iPhone with coding. But there one HTML coding with JavaScript. But when i run the coding the simulator and device show's only the HTML tag contents.
I followed this below link only:
"http://docs.phonegap.com/en/2.0.0/cordova_contacts_contacts.md.html#Contacts"
I have attach the coding and Screen Short:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.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() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
Screen Short:
Please help me to solve the issue. I have followed all the instruction from that above link. But I didn't get the solution. Thanks in advance.

You need to save your contact.
The documentation states :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
function onDeviceReady() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}

var myContact = navigator.contacts.create({"displayName": "Test User"});
Full Example
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
try {
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
// populate some fields
var name = new ContactName();
name.givenName = "Jane";
name.familyName = "Doe";
contact.name = name;
// save to device
contact.save(function(){
alert("Save Success");
},function(){
alert("Error...");
});
} catch(_err) {
alert(_err)
}
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
OR You can find more option for contact api.
I think you have not read document. i have also edited my answers please check once again.
Description :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
http://docs.phonegap.com/en/1.0.0/phonegap_contacts_contacts.md.html#contacts.create

Related

LinkedIn Javascript SDK Retrieve Profiles

I am trying to retrieve any Profile data with the LinkedIn SDK right now. I am only able to retrieve my own data. Is there a way to retrieve like any Profile data or search for profiles with xyz Name and Show the results? I can't find usefull Information about this, neither in the offical documentation or elsewhere.
<!DOCTYPE html>
<html>
<head>
<title>LinkedIn Javascript Api Hello World</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: xxxxxxxxxxxxxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad(){
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
var member = profiles.values[0];
//var id=member.id;
//var firstName=member.firstName;
//var lastName=member.lastName;
//var photo=member.pictureUrl;
//var headline=member.headline;
document.getElementById("profiles").innerHTML =
"<p id=\"" + member.id + "\">Hello " + member.firstName + " " + member.lastName + "</p>";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="profiles"></div>
</body>
</html>
Thank you in advance.
There are only 2 ways to do:
Use Oauth2. This means you have to get access token before you search profile by API.
Refer to this, you must be one of Linkedin Partners.

How do I create chat rooms in Firechat?

I am using Firechat and I am able to successfully initiate the chat window. I am using Firebase custom authentication and I can login without any problem. However, I now try to create a new chat room and then enter it. Based on the Firechat documentation I did the following:
<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<script src='https://cdn.firebase.com/js/client/2.0.2/firebase.js'></script>
<link rel='stylesheet' href='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.css' />
<script src='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.js'></script>
</head>
<body>
<script type='text/javascript'>
var fireBase = new Firebase("https://XXXXXXXXX.firebaseio.com/");
function initChat(authData) {
var Firechat = new FirechatUI(fireBase, document.getElementById('firechat'));
Firechat.setUser(authData.uid, "Username");
Firechat.createRoom("Test chat room", "public");
}
fireBase.authWithCustomToken("UNIQUE_TOKEN", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Login successful", authData);
initChat(authData);
}
});
</script>
<div id='firechat'>
</div>
</body>
</html>
In the javascript console I can see that login is successful:
Login successful Object { auth: Object, expires: XXXXXXXXX, token: "XXXXXXXX…", uid: "XXXXXX", provider: "custom" }
But the createRoom function is not found:
TypeError: Firechat.createRoom is not a function
Any idea what is going wrong here?
From the docs:
Firechat.createRoom(roomName, roomType, callback(roomId))
Creates a new room with the given name (string) and type (string - public or private) and invokes the callback with the room ID on completion.
It would seem that you do not have a callback.
Firechat.prototype.createRoom = function(roomName, roomType, callback) {
var self = this,
newRoomRef = this._roomRef.push();
var newRoom = {
id: newRoomRef.name(),
name: roomName,
type: roomType || 'public',
createdByUserId: this._userId,
createdAt: Firebase.ServerValue.TIMESTAMP
};
if (roomType === 'private') {
newRoom.authorizedUsers = {};
newRoom.authorizedUsers[this._userId] = true;
}
newRoomRef.set(newRoom, function(error) {
if (!error) {
self.enterRoom(newRoomRef.name());
}
if (callback) {
callback(newRoomRef.name());
}
});
};
Source: https://firechat.firebaseapp.com/docs/firechat.html
So it turns out that there are two classes (is that the right word) used in the Firechat javascript plugin:
var chat = new FirechatUI
var chat = new Firechat
Because they seem so similar I did not notice the difference. Nowhere in the documentation have I been able to find details of the FirechatUI instance (even though this code is recommended on the github readme).
So anyway, the thing is that new FirechatUI loads the actual UI for the chat. new Firechat loads the API that allows you to talk to the chat plugin (but NOT to the UI). This is an important difference. The documentation found here only relates to the API so if you initiate a new Firechat instance. However, the trick is to get the UI up and running and then interact with it directly (doing things like creating new rooms or entering rooms). I have honestly not found out how to do this the official/recommended way. The only thing I've been able to come up with is a hack. It's ugly, but it works. The code below includes functionality to create a new chat room (using Firechat) and to open a particular chatroom in the UI (that bit is hacked as I couldn't find a way to interact with the UI directly).
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Title</title>
<!-- jQuery -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<!-- Firebase -->
<script src='https://cdn.firebase.com/js/client/2.1.0/firebase.js'></script>
<!-- Firechat -->
<link rel='stylesheet' href='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.css' />
<script src='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.js'></script>
<!-- This plugin here: https://gist.github.com/buu700/4200601 -->
<script type="text/javascript" src="js/arrive.js"></script>
<style type="text/css">
#firechat{width:400px}
</style>
</head>
<body>
<h1>Test</h1>
<script type='text/javascript'>
var fireBase = new Firebase("https://XXXXXX.firebaseio.com/");
function roomChatSetup(authData) {
var chat = new Firechat(fireBase);
chat.setUser(authData.uid, "My User Name", function(user) {
console.log("Creating chatroom...");
chat.createRoom("New Chatroom Name", "public", function(roomId) {
console.log("Created room "+roomId);
});
$("#firechat").html("<div class='alert alert-success'>Your chatroom has been set up. Refresh to view</div>");
});
}
function initChat(authData) {
var chatUI = new FirechatUI(fireBase, document.getElementById('firechat'));
chatUI.setUser(authData.uid, "My User Name");
console.log("Simulating clicks...");
$("#firechat-tab-content div.tab-pane").waitUntilExists(function(){
console.log("Close all other tabs by simulating clicking the X button");
$("#firechat-tab-content div.tab-pane:not(#XXXXXXXXX) a.close").click(); // XXXXX should have the chatroom name of the one you want to open
});
$("#firechat-btn-rooms").waitUntilExists(function(){
$("#firechat-btn-rooms").click();
console.log("Open submenu to load all possible rooms");
});
$("li[data-room-id='XXXXXXXXXXXXX']").waitUntilExists(function(){
$("li[data-room-id='XXXXXXXXXX'] a").click();
console.log("Simulating clicking on chatroom XXXXXXXXXXXXXX");
});
}
fireBase.authWithCustomToken("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Login successful", authData);
// Here you can use a programming language to decide. If you already have a
// chatroom, run initChat. If you don't, run createRoom. I haven't been
// able to run them both at the same time.
initChat(authData);
// or:
roomChatSetup(authData);
}
});
</script>
<div id="firechat"></div>
</body>
</html>
The FirechatUI object is separate from the Firechat object. FirechatUI does not have the same methods that Firechat does.
In order to get the associated Firechat object from a FirechatUI object you can do the following:
let chatUI = new FirechatUI(chatRef, document.getElementById("firechat-wrapper"));
let chat = chatUI._chat;
You can then do any normal Firechat operations without any issues.
chat.setUser(user.uid, firstName, function(user) {
chat.resumeSession();
});
Please keep in mind that the _chat element is not really supposed to be used (as you can tell from the naming convention), but since FirechatUI does not properly expose enough functionality this is probably the cleanest way to do it.

Google+ API doesnt return access_token Javascript

We have an application that relies upon Google to authenticate its users against our google apps account and then do some serverside verification and group lookups.
Recently google changed the name of the object that held the access_token variable which we require to authenticate. In the docs (https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile) it says that access_token is available from the getAuthResponse() method, however when i use this it comes back as undefined. Inspecting the object after console.log() reveals all the other fields mentioned except access_token. I'm worried that Google will change the object again in the future and leave us without our application.
Here is the code.
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script>
//This happens after the user has authenticated with Google and has been passed
//back to the page
function onSignIn(googleUser) {
//Check to see whether the user is trying to sign out.
if (window.location.href.indexOf("signOut=1") !== -1) {
//Sign them out of the application.
signOut();
//redirect them to the same page, without the signOut query string so they can log back in if want
window.location.href='googlesigninform.html'
return false;
}
//Grab the token, access token and email.
var _id = googleUser.getAuthResponse().id_token; //This works
var _accessToken = googleUser.Ka.access_token; //This works but changed from googleUser.B.access_token
var profile = googleUser.getBasicProfile(); //Works
console.log(googleUser.access_token); //Undefined
console.log(googleUser.getAuthResponse().access_token);//Undefined
//Make a post request to the API
makePostRequest(_id, _accessToken, profile.getEmail());
}
What is the correct way to access the access_token variable?
If you need to use access token you are using the wrong type of google signin flow.
You should follow this page: https://developers.google.com/identity/sign-in/web/server-side-flow
What you did implement is google Sign-In to identify users (https://developers.google.com/identity/sign-in/web/)
Which only provides a unique id per user because it is meant to authenticate the user for your own service and not to give an access token to use for other Google services later on.
I believe your problem is that your application is lacking the necessary google-signin-scope.
To answer your question i created an app from the ground using the Google Developer Console. The application is very simple like the one this this tutorial.
The entire application consists of a simple HTML that loads the google API and has a callback called onSignIn (like yours).
Here's the entide code of the application:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="PLACE_YOUR_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
var response = googleUser.getAuthResponse(),
idToken = response['id_token'],
accessToken = response['access_token'];
console.dir('id token: ' + idToken);
console.dir('access token: ' + accessToken);
}
</script>
</body>
</html>
As you can see, the difference between my app and yours is that yours is lacking the first META attribute.
Well i have a hack work around that gets the access_token from the variable.
function findAccessToken(googleUser) {
var returnValue;
Object.getOwnPropertyNames(googleUser).forEach(function (val, idx, array) {
console.log(val + ' -> ' + googleUser[val]);
Object.getOwnPropertyNames(googleUser[val]).forEach(function (vals, idxs, arrays) {
if (vals === "access_token") {
console.log("true");
returnValue = googleUser[val][vals];
}
});
});
return returnValue;
}
Surely this can't be the most elegant solution. If someone could point in the righter direction that would be good.
Here is the code for sign in using google.
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>
Try this
var _access_token = GoogleUser.getAuthResponse().access_token

“Uncaught ReferenceError: cordova is not defined”

I'm trying use the Facebook slider menu on iOS, with the PhoneGap. The problem is that I am not able to insert data in sqlite, When clicking on the save button I got this error:
"Uncaught ReferenceError: cordova is not defined".
This is the source:
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="../../css/index.css" />
<script type="text/javascript" src="../../js/SQLitePlugin.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("device ready");
}
function insert() {
console.log("Run1");
var db = window.sqlitePlugin.openDatabase({
name: "PHR.db"
});
db.transaction(function(tx) {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS SignUp (firstname VARCHAR,lastname VARCHAR,email VARCHAR, password VARCHAR ,question1 VARCHAR, answer1 VARCHAR,question2 VARCHAR,answer2 VARCHAR, question3 VARCHAR,answer3 VARCHAR)'
);
});
db.transaction(function(tx) {
var fname = document.getElementById("fn").value;
var lname = document.getElementById("ln").value;
var emai = document.getElementById("em").value;
var passw = document.getElementById("pas").value;
var qus1 = document.getElementById("qs1").value;
var ans1 = document.getElementById("as1").value;
var qus2 = document.getElementById("qs2").value;
var ans2 = document.getElementById("as2").value;
var qus3 = document.getElementById("qs3").value;
var ans3 = document.getElementById("as3").value;
tx.executeSql(
'INSERT INTO SignUp (firstname,lastname,email, password ,question1 , answer1 ,question2 ,answer2 , question3,answer3) VALUES (?,?,?,?,?,?,?,?,?,?)', [
fname, lname, emai, passw, qus1, ans1, qus2, ans2, qus3,
ans3
]);
}, null);
});
}
</script>
you need to add
<script type="text/javascript" src="cordova.js"></script>
in the head tag
In your code :
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="../../css/index.css" />
<script type="text/javascript" src="cordova.js"></script> //--> You missed this line.
<script type="text/javascript" src="../../js/SQLitePlugin.js"></script>
<script type="text/javascript" charset="utf-8">
//Remaining code goes here ... ...
add the cordova script in your html file, int he head
I was in a very tricky situation with reactjs + cordova for mobile. This was specifically happening when trying to leverage cordova's datadirectory field on a mobile device, the prod build would error out.
The solution that worked for me
Simply reference window.cordova instead of cordova

How do I set this.location.href to a specific subdomain location

This is a version of Gatekeeper, I'm trying to get this to go to a subdomain of my website but it only goes to specific files on my main domain. Basically I enter 404 and it takes me to: http://mysite.com/404.html and I want it to go to: http://subdomain.mysite.com/404.html I'm kinda new to this but I think I need to change
if (password) { this.location.href = password + ".html"; }
to where the this.location.href doesn't read my current url but the url I specifically want.
Here is the full example code:
<HTML>
<HTML>
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT language="JavaScript"><!--
/*********************************************************
GateKeeper v2.3 - by Joe Barta
http://www.pagetutor.com/keeper/
Permission is granted to freely use this script.
**********************************************************/
function GateKeeper() {
var password = prompt("Password required:", "");
if (password) { this.location.href = password + ".html"; }}
//--></SCRIPT>
</HEAD>
<BODY>
Click here for my secret page!
</BODY>
</HTML>
Any ideas or suggestions? Thanks in advance!

Categories