PhoneGap/Cordova Plugin - how to set up? - javascript

Ive installed the Calendar plugin for iOS successfully (I think) from here:
https://github.com/phonegap/phonegap-plugins/tree/master/iOS/CalendarPlugin
However I just cant seem to get it working.
So far heres what I have done:
Dropped the calendar .h and .m files into the plugins folder of my
project.
Added the calendar.js file to my directory structure and linked in
the header
Added the EventKit and EventKitUI frameworks to my project
Added the term calendarPlugin to my cordova.plist file
And 5. Added the code below to the page one which I want to save:
window.plugins.calendarPlugin.prototype.createEvent = function(title,location,notes, startDate, endDate){
var title= "My Appt";
var location = "Los Felix";
var notes = "me testing";
var startDate = "2012-11-23 09:30:00";
var endDate = "2012-11-23 12:30:00";
cal.createEvent(title,location,notes,startDate,endDate);
}
$(document).ready(function() {
cal = window.plugins.calendarPlugin;
var cal;
$('.calinfo').live('click', function() {
var desiredValue = $(this).parent().prev().find('.calendar').val();
console.log(desiredValue);
var calInfo = desiredValue.split(',');
createEvent(calInfo[0], calInfo[1], calInfo[2], calInfo[3], calInfo[4]);
});
});
When I run it noting happens. Have I missed something?

Dont't use $(document).ready(function());. Rather use device ready. Call the function onBodyLoad() on body load.
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
deviceready = true;
}
//////////////////////////////////
function onDeviceReady()
{
// Your code goes here
}

Related

Dojo function not fired only on IE7

I am new to dojo. I am debugging a js that's using dojo 1.9.1
require(["dojo/ready", "dojo/hash", "dojo/topic"], function (ready, hash, topic) {
ready(function(){
try {
dimXsl = getDimensionXSLT("somepath.xsl"); // 1
topic.subscribe("/dojo/hashchange", callback); // 2
var djConfig = ""; // 3
djConfig.hashPollFrequnecy = 10; // 4
} catch (e) {
console.log('Error ' + e);
}
});
});
function callback() {// blbla }
The above code works for IE8 and above to fire callback(), but not IE7.
My investigations:
I searched Dojo documentation. for version 1.7, the doc https://dojotoolkit.org/reference-guide/1.7/dojo/hash.html suggests a blank html page. So, I did below:
change js dojo link to 1.7 when href it.
Added blank blank.html in project, and replaced //3-4 with
var dojoConfig = "";
dojoConfig.hashPollFrequnecy = 10;
dojoConfig.dojoBlankHtmlUrl = "/blank.html";
Another replacement //3-4 try was:
var dojoConfig = {
hashPollFrequnecy: 10,
dojoBlankHtmlUrl: "/blank.html"
};
But no luck. I also tried to carry above changes with dojo version 1.9.1, but still no luck.
Any ideas please? Thank you very much.

Javascript on click - two parts to the function but only one works at a time

I have two server side php scripts:
1: /addit.php - which creates a pdf file on server based on current ID given
2: /viewit.php - which downloads the pdf file to the browser window.
Both these scripts work fine btw.
However I want to combine a single onclick function to run "addit.php" and then view the file by opening the file "view.php".
So I am using the original code that was creating the file ok and then adding in a window.location but they won't work together. If I remove the window.location the first part of code works fine, If I include it, the first part stops working and only the window.location works.
Sorry for being stupid, thanks.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php',
{ list_entry_id: id },
$("#infobox_data_button2").fadeTo(1001,.33)
);
});
window.location="myaddress/viewit.php";
};
You should move window.location="myaddress/viewit.php"; to ajax callback as below. Otherwise it fires before you get response from server.
$.post('myaddress/addit.php',
{ list_entry_id: id },
function() {
$("#infobox_data_button2").fadeTo(1001,.33);
window.location="myaddress/viewit.php";
}
);
The window.location is out of the event. While you run the ajax (asynchronous) to 'myaddress/addit.php' the redirect will occur killing the process.
You need to put the window.location in a success callback, therefore in the event.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php', { list_entry_id: id }, function(data){
$("#infobox_data_button2").fadeTo(1001,.33);
// Here!
window.location="myaddress/viewit.php";
});
});
// Abandoned
//window.location="myaddress/viewit.php";
};

Call Javascript After Saving Calendar Item

I am having a script as below:-
function getColorValue(aId,atitle) {
try{
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle('Item type');
var oListItem = oList.getItemById(parseInt(aId));
clientContext.load(oListItem);
clientContext.executeQueryAsync(function () {
var listItem = oListItem;
var colorname = listItem.get_item('Color_x0020_Name');
if (typeof colorname != 'undefined') {
if (colorname != null) {
$("div[title$='" + atitle + "']").css("background-color", colorname);
}
}
}, onColorQueryFail);
}
catch(e){
}
}
I need to call this script each time after a SharePoint Calendar Item is created.
Can anyone help?
The following JavaScript example demonstrates how to register event that will be triggered after Calendar item is created:
//custom handler that will be triggered after Calendar item is created
function onEventCreated(){
alert('Event has been created...');
}
function registerCalendarEventOnItemCreated(event)
{
var currentCtx = getCurrentContextInfo();
var calContainer = SP.UI.ApplicationPages.CalendarInstanceRepository.lookupInstance(currentCtx.ctxId);
for(var name in calContainer) {
if(calContainer.hasOwnProperty(name)) {
var p = calContainer[name];
if(p instanceof SP.UI.ApplicationPages.CalendarNewFormDialog) {
p.get_events().addHandler("newitemcreated",event);
}
}
}
}
//get current context info
function getCurrentContextInfo()
{
var currentListId = new SP.Guid(_spPageContextInfo.pageListId);
for(var ctxKey in g_ctxDict){
var curCtx = g_ctxDict[ctxKey];
if(curCtx.listName == currentListId.toString()){
return curCtx;
}
}
return null;
}
//register Calendar events
$('body').on('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});
Has been tested against SharePoint 2013/Online
In your case the function getColorValue could be invoked from onEventCreated, for example:
function onEventCreated(){
getColorValue (id,title);
}
How to apply changes
Switch the page into Edit mode
Add Script Editor webpart into page.
Put the specified code by wrapping it using script tag code into the Script Editor, for example: <script type="text/javascript">{JavaScipt code goes here}</script>
Save the page
Results
Create an Event Receiver with List Item Events for type and Calendar for Source then check 'An item is being added' in handling the event.
Then in the code behind of your Event Receiver:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//Call your function through this
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);
}
Hope that helps :)
I know this is an old question, but there is an issue with the solution given.
I had a requirement to implement an workaround to the missing Resource Reservation feature in Sharepoint online. It was not possible to use an approach more suitable to the Modern Experience, due its dependency of Azure (no Azure subscription available for it), so I use Sharepoint API calls to perform the the same functionality of Resource Reservation.
To use the Sharepoint API, some Ajax calls were needed. But I observed that two calls were executed for each request.
The point is when you register calendar events, it is needed to attach the click event using one, as seen below, to prevent the click event to be fired more than once.
//register Calendar events
$('body').one('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});

Start speech recognizer on Android using Phonegap

Currently I'm making a Phonegap application.
I want to combine augmented reality en speech input.
There is a plugin for Phonegap called SpeechRecognizer, But I can't get it to work.
My header:
<script type="text/javascript" src="cordova-2.6.0.js"></script>
<script type="text/javascript" src="SpeechRecognizer.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function speechOk() {
alert('speech works');
}
function speechFail() {
alert("speech doesn't work");
}
function onDeviceReady() {
window.plugins.speechrecognizer.init(speechOk, speechFail);
}
$("#micButton").bind("touchstart", function() {
var requestCode = 4815162342;
var maxMatches = 1;
var promptString = "What do you want?";
window.plugins.speechrecognizer.startRecognize(speechOk, speechFail, requestCode, maxMatches, promptString);
});
</script>
A picture of the project (config.xml):
Thanks in advance
Is not your fault, the SpeechRecognizer.java has a bug inside.
I had the same problem and I solved it with just replacing the Speech Recognizer plugin with and older version (like 2.0.0), you can download it from github.
It worked for me with Phonegap 2.5.0, guess it works in 2.6.0.
There were a few problems.
First of all, the SDK version wasn't right. If you use the new cordova you also have to use the newest version of the plugin. This version requires SDK 15 or higher. (android manifest -> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="17" />).
After that, for some reason the plugin init does not return anything.
I just triggerd the: window.plugins.speechrecognizer.startRecognize(); function on a button click, and it executes.
The javascript (you need jQuery for this code):
$("#micButton").bind("touchstart", function() {
var requestCode = 4815162342;
var maxMatches = 1;
var promptString = "What do you want?";
window.plugins.speechrecognizer.startRecognize(speechOk, speechFail, requestCode, maxMatches, promptString);
});
function speechOk(result) {
var match, respObj;
if (result) {
respObj = JSON.parse(result);
if (respObj) {
var response = respObj.speechMatches.speechMatch[0];
$("#searchField").val(response);
$("#searchButton").trigger("touchstart");
}
}
}
function speechFail(m) {
navigator.notification.alert("Sorry, I couldn't recognize you.", function() {}, "Speech Fail");
}
'#micButton' is the button you have to press to start the android voice recognition
'#searchField' is a input field wich gets the result from the voice recognition
Thanks to MrBillau for the good advice.

Phonegap onDeviceOnline

I am using the folowing script to check if device is online or offline:
function checkConnection() {
document.addEventListener("online", onDeviceOnline, false);
document.addEventListener("offline",onDeviceOffline, false);
function onDeviceOnline(){
loadZive();
loadMobil();
loadAuto();
};
function onDeviceOffline(){
alert("deviceIsOffline");
};
};
checkConnection();
Then I have this function to load feed:
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("style","text-align: right; margin-top: 5px;");
var publishedDate = new Date(entry.publishedDate);
publishedDateConverted = convertTime(publishedDate);
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.setAttribute("style","white-space: normal;")
h3.appendChild(document.createTextNode(entry.title));
p.setAttribute("style","white-space: normal;")
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.setAttribute("style","white-space: normal;")
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
First I load second script, then first. But I cant see anything. If I turn my app on then I see page layout for abou 1 sec then (probably after loading first script) function onDeviceOnline() happens and I can see only blank page. But it should load feeds into existing template.
IMHO onDeviceOnline function happens after loading the page template and therefore it cant import feeds. If I create function like this:
function loadFeeds(){
loadZive();
loadMobil();
loadAuto();
};
then everything works fine so I think it has something to do with online and offline eventlisteners. It also didnt work when I put checkconnection into onDeviceReady function so it should not be the problem. So is there any way to check if device is online and if it is then use js file to load feeds?
EDIT: I have used Simon McDonald suggestion and created code like this:
function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(){
navigator.app.exitApp();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
if (networkState == "none"){
alert("no network connection");
}
else{
loadZive();
loadMobil();
loadAuto();
};
};
checkConnection();
};
With this code alerts are working perfectly for device online and device offline but when I try to loadFeed I get the same result as before (page layout loads and then everything changes to blank page).
The problem is that you are adding a "online" event listener in device ready event listener but the device is already on line so the event will not fire again until there is a change in connectivity. In your device ready event listener you should check the value of navigator.connection.network.type and make sure it isn't NONE.
http://docs.phonegap.com/en/2.0.0/cordova_connection_connection.md.html#connection.type

Categories