How to use Rohfosho/CordovaCallNumberPlugin - javascript

How to use this plugin with onSuccess and onError function my code is this:
$scope.callNumber= function (){
var number = 3333322456;
var onSuccess=function(number){
alert("invia messaggio");
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
window.plugins.CallNumber.callNumber(onSuccess, onError, number);
}
but it doesn't work.

I was able to make it work using the code below.
function onSuccess(result){
console.log("Success:"+result);
}
function onError(result) {
console.log("Error:"+result);
}
$scope.callNumber = function(number){
console.log("Launching Calling Service for number "+number);
window.plugins.CallNumber.callNumber(onSuccess, onError, number, false);
}
I attached this to my html element as follows.
<button class="button icon ion-ios-telephone" ng-click="callNumber(0123456789)">Call</button>

Follow this tutorial. It helps me http://rickluna.com/wp/2012/02/making-a-phone-call-from-within-phonegap-in-android-and-ios/
But it's not about this plugin. it's a different way to call immediately via cordova.

Related

How can I concatenate .load() jquery method?

I am using the cordova plugin phonegap-plugin-portrait-barcodescanner on my PhoneGap App.
So I can't combine the variable result and Scanner result. I have that combine this results on .load(VAR + SCANNER RESULT);
In javascript alert it's ok. But in Load(); not working.
Thankks!
$('#scan').click(function() {
cordova.plugins.barcodeScanner.scan(
function(result) {
var irisUrl = 'http://www.vcomm.com.br/';
$('#Load').load(irisUrl + result.text);
alert("http://www.vcomm.com.br/" + result.text);
},
function(error) {
alert("Scanning failed: " + error);
}
);
});
maybe you have to try somethig like this:
$('#Load').load(irisUrl, function () {
irisUrl = $(this) + result.text();
});
or something like this. I'm not sure because I don't know the result of that alert in your example. What do you want to see etc.

My cordova application don't want to run, I don't know why

I'm developing an application in Cordova. This app should be able to capture a video when you press the capture button, and then upload it on a specific server.
But I have a problem with the capture API. When I run it on emulator or a physical device, nothing happens, and on ripple, an error is returned.
My HTML code is here
<div class="button">
<div class="button1">
<button id="captureVideo" class="btn btn-lg btn-primary">launch a capture</button>
</div>
</div>
And my js
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("captureVideo").addEventListener("click", function () {
document.addEventListener("deviceready", onDeviceReady, false);
});
})
function onDeviceReady() {
console.log(navigator.device.capture);
navigator.device.capture.captureVideo(captureSuccess, captureError, { limit: 1 });
console.log("Record launched !");
}
// Called when capture operation is finished
function captureSuccess(mediaFiles) {
navigator.notification.alert("Capture Success");
/*var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}*/
}
// Called if something bad happens
function captureError(error) {
navigator.notification.alert("Capture failed");
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// Upload files to server
/*function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function (result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function (error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}*/
Thanks a lot for your answer :)
As demanded, I put my code directly here instead of pastebin.
Finally found ! It was cause my plugin wasn't loaded in the app.

Chrome extension Native messaging synchronization

I have problem with Native messaging synchronization on windows. I am trying to synchronize the message between backgroundPage and hostApp. normally, we use native messaging like this:
//popup.js
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function sendNativeMessage() {
message = {"command": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.google.chrome.example.dmtest1";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>");
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
updateUiState();
});
<html>
<head>
<script src='./popup.js'></script>
</head>
<body>
<button id='connect-button'>Connect</button>
<input id='input-text' type='text' />
<button id='send-message-button'>Send</button>
<div id='response'></div>
</body>
</html>
but the sendNativeMessage() and onNativeMessage(..) functions are asynchronous, and I want to make them synchronous. I tried the method below but it failed to get the response data from the host(c++ exe), and it made chrome crash.
function sendNativeMessage() {
var message = {"command": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
port.onMessage.addListener(function(msg) {
appendMessage("Receive message: <b>" + JSON.stringify(msg) + "</b>");
});
}
How can I do this, is it possible, Any help?
After several days of search and test, I finally found an answer(here: how to handle chrome.runtime.sendNativeMessage() in native app) and solved my problem. I give up the idea about making my callback functions synchronous, I just use another way of communicating between Chrome extension backpage and my local host app. Instead of var port = chrome.runtime.connectNative(hostName);port.onMessage.addListener(onNativeMessage);port.postMessage(message); I used the code below to send and receive data between backpage and hostapp, and it is synchronous:
chrome.runtime.sendNativeMessage(hostName, sendMsg, function(response) {
if (chrome.runtime.lastError) {
alert("ERROR: " + chrome.runtime.lastError.message);
} else {
sendResponse({farewell: ParseJSON(response)});
}
});

Call JS function from code behind C#

I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>
Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.
Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.
The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}

Converting an MVC4 Web API Application to Phonegap Android Application

I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.

Categories

Resources