I am looking to pull the audit logs on the below listed resource via the API.
The audit logs should be turned on according to the library settings, but I can't seem to find the correct path to get the details. Suggestions are appreciated.
API Call
https://collab.iad.ca.inet/teams/OPPE/Operational Performance Tools/_api/Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)
Current Response
<?xml version="1.0" encoding="utf-8"?>
<entry xml:base="https://collab.iad.ca.inet/teams/OPPE/Operational%20Performance%20Tools/_api/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:etag=""5"">
<id>4fb4f10c-3abc-4c4e-b501-fe97d5072e1d</id>
<category term="SP.Data.Shared_x0020_DocumentsItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
<link rel="edit" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FirstUniqueAncestorSecurableObject" type="application/atom+xml;type=entry" title="FirstUniqueAncestorSecurableObject" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/FirstUniqueAncestorSecurableObject" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/RoleAssignments" type="application/atom+xml;type=feed" title="RoleAssignments" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/RoleAssignments" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/AttachmentFiles" type="application/atom+xml;type=feed" title="AttachmentFiles" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/AttachmentFiles" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ContentType" type="application/atom+xml;type=entry" title="ContentType" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/ContentType" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/GetDlpPolicyTip" type="application/atom+xml;type=entry" title="GetDlpPolicyTip" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/GetDlpPolicyTip" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesAsHtml" type="application/atom+xml;type=entry" title="FieldValuesAsHtml" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/FieldValuesAsHtml" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesAsText" type="application/atom+xml;type=entry" title="FieldValuesAsText" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/FieldValuesAsText" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesForEdit" type="application/atom+xml;type=entry" title="FieldValuesForEdit" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/FieldValuesForEdit" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/File" type="application/atom+xml;type=entry" title="File" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/File" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Folder" type="application/atom+xml;type=entry" title="Folder" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/Folder" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ParentList" type="application/atom+xml;type=entry" title="ParentList" href="Web/Lists(guid'4fda26e5-103a-4b44-ade5-0c6eb6bc981e')/Items(1)/ParentList" />
<title />
<updated>2017-09-22T17:32:14Z</updated>
<author>
<name />
</author>
<content type="application/xml">
<m:properties>
<d:FileSystemObjectType m:type="Edm.Int32">0</d:FileSystemObjectType>
<d:Id m:type="Edm.Int32">1</d:Id>
<d:ContentTypeId>0x010100ABBF36DE0421214A8F4689DD7BB5FC63</d:ContentTypeId>
<d:Title>Intact Pro-Rata Calculator</d:Title>
<d:SharedWithUsersId m:null="true" />
<d:ID m:type="Edm.Int32">1</d:ID>
<d:Created m:type="Edm.DateTime">2017-09-01T21:52:45Z</d:Created>
<d:AuthorId m:type="Edm.Int32">15</d:AuthorId>
<d:Modified m:type="Edm.DateTime">2017-09-21T22:59:39Z</d:Modified>
<d:EditorId m:type="Edm.Int32">15</d:EditorId>
<d:OData__CopySource m:null="true" />
<d:CheckoutUserId m:null="true" />
<d:OData__UIVersionString>5.0</d:OData__UIVersionString>
<d:GUID m:type="Edm.Guid">4fe5308e-c8a9-469c-ae58-db4c3b9e8a1b</d:GUID>
</m:properties>
</content>
</entry>
The Audit API is not available via the CSOM/REST APIs. SP.Change class which provides the similar capabilities and is exposed via CSOM/REST API could be used instead.
The following example demonstrates how to retrieve changes per list and print change time and type name:
var listTitle = "Documents";
var changeQuery = {
"Add":true,
"Update":true,
"DeleteObject":true,
"File":true,
"Item":true
};
getListChanges(_spPageContextInfo.webAbsoluteUrl,listTitle, changeQuery)
.then(function(data){
data.d.results.forEach(function(item){
console.log(item.Time + ":" + getChangeTypeName(item.ChangeType));
});
})
.fail(function(error){
console.log(error);
});
where
function getListChanges(webUrl,listTitle,changeQuery)
{
var payload = {
'query' : changeQuery
};
payload.query['__metadata'] = { 'type': 'SP.ChangeQuery' };
var properties = {
webUrl: webUrl,
requestUrl: "/_api/web/lists/getbytitle('" + listTitle + "')/getchanges",
payload: payload,
action: "InvokeMethod"
};
return executeRequest(properties);
}
function getChangeTypeName(id){
var mappings = {
1 : "Add",
3 : "DeleteObject",
2: "Update"
}
return mappings[id];
}
function executeRequest(options) {
options.headers = options.headers || {};
options.headers["Accept"] = "application/json;odata=verbose";
options.headers["Content-Type"] = "application/json; odata=verbose";
options.headers["Accept-Language"] = _spPageContextInfo.currentCultureName;
options.action = options.action || "Read";
switch (options.method) {
case "Update":
options.headers["IF-MATCH"] = "*";
options.headers["X-HTTP-Method"] = "MERGE";
break;
case "Delete":
options.headers["IF-MATCH"] = "*";
options.headers["X-HTTP-Method"] = "DELETE";
break;
}
var ajaxOptions =
{
url: options.webUrl + options.requestUrl,
type: options.method == "Read" ? "GET" : "POST",
headers: options.headers
};
if ("payload" in options) {
ajaxOptions.data = JSON.stringify(options.payload);
ajaxOptions.type = "POST";
}
if(options.action != "Read"){
ajaxOptions.headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
return $.ajax(ajaxOptions);
}
Related
I am trying to bind data in a dropdown (sap.m.Select) from a service but data is not getting displayed in the dropdown. Below is my code:
Controller
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], function (Controller, JSONModel) {
"use strict";
return Controller.extend("hmel.TravelandGuestHouse.controller.CloneTravelRequest", {
onInit: function () {
this.router = sap.ui.core.UIComponent.getRouterFor(this);
//For Train Name
this.addmodel = new JSONModel();
this.getView().setModel(this.addmodel, "Model");
this.actionTemp = this.getView().byId("trainName").clone();
this.detailModel = sap.ui.getCore().getModel("detailModel");
this.getView().setModel(this.detailModel, "detailModel");
this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
},
_handleRouteMatched: function(evt) {
if (evt.getParameter("name") !== "CloneTravelRequest") {
return;
}
var that = this;
that.getView().byId("trainName").bindAggregation("items", {
path: "/TravelPrpTrainDetails",
template: that.actionTemp
});
}
});
});
View
<m:Select id="trainName" selectedKey="{detailModel>/TrainName}">
<core:Item key="{ID}" text="{TrainName}"/>
</m:Select>
Data is coming in the below form and I just want to extract TrainName attribute from it:
<entry>
<id>http://________________________/TravelPrpTrainDetails(36)</id>
<category
term="WCFODataService.TravelPropTrainDetails"
scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
/>
<link
rel="edit"
title="TravelPropTrainDetails"
href="TravelPrpTrainDetails(36)"
/>
<title />
<updated>2019-01-03T06:02:36Z</updated>
<author>
<name />
</author>
<content type="application/xml">
<m:properties>
<d:SerialNo m:type="Edm.Int32">2</d:SerialNo>
<d:ID m:type="Edm.Int32">36</d:ID>
<d:TrainName>AJMER ASR EXPRESS 19611</d:TrainName>
</m:properties>
</content>
</entry>
Hi Swappy, the solution is pretty simple. Your item's binding should use the same model name of the parent binding. In this case, you should have:
<core:Item key="{detailModel>Value}" text="{detailModel>Value}"/>
In general, you should always use this rule when your model is not the default one (default is when the model has no name).
<ComboBox
items="{ModelName>/ListOfValues}">
<core:Item key="{ModelName>Key}" text="{ModelName>Value}"/>
</ComboBox>
If you're using the default model you should use this kind of template:
<ComboBox
items="{/ListOfValues}">
<core:Item key="{Key}" text="{Value}"/>
</ComboBox>
Is it possible to disable row selector for particular rows. setEnable method is not available for sap.ui.table. Please find the attached screenshot for better understanding.
please go through the following code. It might help you.
sap.ui.controller("my.controller", {
onInit: function() {
var model = new sap.ui.model.json.JSONModel([
{Product: "Power Projector 4713", Weight: "33"},
{Product: "Gladiator MX", Weight: "33"},
{Product: "Hurricane GX", Weight: "45"},
{Product: "Webcam", Weight: "33"},
{Product: "Monitor Locking Cable", Weight: "41"},
{Product: "Laptop Case", Weight: "64"}
]);
var vw = this.getView();
vw.setModel(model);
// disable checkboxes
var tbl = vw.byId('tblProduct');
tbl.addDelegate({
onAfterRendering: function() {
var header = this.$().find('thead');
var selectAllCb = header.find('.sapMCb');
selectAllCb.remove();
this.getItems().forEach(function(r) {
var obj = r.getBindingContext().getObject();
var enabled = parseInt(obj.Weight, 10) > 40;
var cb = r.$().find('.sapMCb');
var oCb = sap.ui.getCore().byId(cb.attr('id'));
oCb.setEnabled(enabled);
});
}
}, tbl);
}
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#chartView').html()
}).placeAt('content');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
<script id="chartView" type="sapui5/xmlview">
<mvc:View
controllerName="my.controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<App>
<pages>
<Page title="Table CheckBox Disable" class="marginBoxContent" >
<content>
<Table id="tblProduct" mode= "MultiSelect"
selectionChange = "rowSelect"
items="{/}">
<columns>
<Column>
<Label text="Product" />
</Column>
<Column>
<Label text="Weight" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{Product}" />
<Text text="{Weight}" />
</cells>
</ColumnListItem>
</items>
</Table>
</content>
</Page>
</pages>
</App>
</mvc:View>
</script>
</head>
<body class="sapUiBody">
<div id='content'></div>
</body>
</html>
Regards,
Farooq.
I have the following list, but it is not reacting to any of the events that I'm using.
In the method onSelectionChange i have breakpoints and is updating the label, but it is for some reason not reaching this. The onSearch method is working fine.
I'm using the sapui5
<mvc:View
height="100%"
controllerName="Tasks.CompletedTasks.view.CompletedTasks"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
<SearchField
liveChange="onSearch"
width="100%" />
<Label id="label" text="test">
</Label>
<List
id="idList"
items="{/results}"
select="onSelectionChange"
>
<items>
<StandardListItem
title="{TaskTitle}"
description="{InstanceID}"
icon="sap-icon://task"
iconDensityAware="false"
iconInset="false"
/>
</items>
</List>
Code:
jQuery.sap.require("jquery.sap.resources");
jQuery.sap.require("sap.ui.model.Filter");
jQuery.sap.require("sap.ui.model.FilterOperator");
jQuery.sap.require("Tasks.CompletedTasks.util.ModelBuilder");
sap.ui.controller("Tasks.CompletedTasks.view.CompletedTasks", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf cscompletedtasks.CompletedTasks
*/
onInit: function() {
//this.getView().bindElement("/results");
},
onSelectionChange : function (oEvt) {
var oList = oEvt.getSource();
var oLabel = this.getView().byId("label");
oLabel.setText("event");
},
onSearch : function (oEvt) {
// add filter for search
var aFilters = [];
var sQuery = oEvt.getSource().getValue();
if (sQuery && sQuery.length > 0) {
var filter = new sap.ui.model.Filter("TaskTitle", sap.ui.model.FilterOperator.Contains, sQuery);
aFilters.push(filter);
}
// update list binding
var list = this.getView().byId("idList");
var binding = list.getBinding("items");
binding.filter(aFilters, "Application");
}
});
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script id="sap-ui-bootstrap"
src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-resourceroots='{"Tasks.CompletedTasks" : "./" }'>
</script>
<script>
new sap.ui.core.ComponentContainer( {
name : "Tasks.CompletedTasks"
}).placeAt("content");
</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>
The select event work if you set the mode of selection on the list.
<List
id="idList"
items="{/results}"
select="onSelectionChange",
mode="" //Type of mode you required SingleSelect,MultiSelect, Delete default it is None.
>
<items>
<StandardListItem
title="{TaskTitle}"
description="{InstanceID}"
icon="sap-icon://task"
iconDensityAware="false"
iconInset="false"
/>
</items>
</List>
refer this link for more information
Please slot this at the top of the function handling the onSelectionChange event:
jQuery.sap.log.setLevel(jQuery.sap.log.LogLevel['INFO']);
jQuery.sap.log.info("*** my onSelectionChange has triggered");
i.e.:
onSelectionChange : function (oEvt) {
jQuery.sap.log.setLevel(jQuery.sap.log.LogLevel['INFO']);
jQuery.sap.log.info("*** my onSelectionChange has triggered");
var oList = oEvt.getSource();
Then check the console of your browser and filter to find the output of this message. (Just in case the event is triggering and your consequent code doesn't do anything. (if you have set the LogLevel elsewhere please ignore)
below is the code snippet, I want to retrieve the selected value, the autocomplete works perfectly fine,
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<script type="text/javascript">
function sayPramod()
{
alert("hiii");
}
</script>
<sx:head />
</head>
<body>
<h1>Struts 2 autocompleter + JSON example</h1>
<s:form >
<s:url id="databaseList" action="databaseJSON"
/>
<sx:autocompleter label="What's your favorite Database Server?"
href="%{databaseList}" name="yourFavDatabase"
/>
<s:submit value="submit" name="submit" onclick="sayPramod();" />
</s:form>
</body>
</html>
The java code is:
package com.krcl.rap.common.menu.action;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class DatabaseJSON {
private Map<String, String> databases = new HashMap<String, String>();
public DatabaseJSON(){
databases.put("Google", "www.google.com");
databases.put("Oracle", "Oracle");
databases.put("PostgreSQL", "PostgreSQL");
databases.put("Microsoft SQL Server", "Microsoft SQL Server");
databases.put("DB2", "DB2");
}
public String execute() {
return Action.SUCCESS;
}
public Map<String, String> getDatabases() {
return databases;
}
public void setDatabases(Map<String, String> databases) {
this.databases = databases;
}
}
struts.xml
<package name="json" namespace="/" extends="json-default">
<action name="databaseJSON" class="com.krcl.rap.common.menu.action.DatabaseJSON">
<result type="json" >
<param name="root">databases</param>
</result>
</action>
</package>
<package name="default" namespace="/" extends="struts-default">
<action name="autoCompleterAction"
class="com.krcl.rap.common.menu.action.AutoCompleterAction"
method="display">
<result name="none">pages/autocompleter-json.jsp</result>
</action>
<action name="resultAction"
class="com.krcl.rap.common.menu.action.AutoCompleterAction" >
<result name="success">pages/result.jsp</result>
</action>
</package>
Use
<sx:autocompleter label="What's your favorite Database Server?"
href="%{databaseList}" name="yourFavDatabase"
id="yourFavDatabase"/>
in your jsp and
var yourFavDb=dojo.widget.byId('yourFavDatabase').getValue();
in your script to get the value. If you want to get the selected value in your Action class it will come on its own, once you submit the form.
I have a weird problem with my first phonegap/cordova app for ios
i copy pasted the examples from
http://docs.phonegap.com/en/2.3.0/cordova_camera_camera.md.html#camera.getPicture
and
http://docs.phonegap.com/en/2.3.0/cordova_media_capture_capture.md.html#capture.captureImage
But when i press any of the buttons nothing happens, unless i double-tap the "home"-button on the iphone afterwards.
Here is my index.html:
<script src="assets/js/cordova.ios.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready to be used!
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
var smallImage = document.getElementById('smallImage');
// Unhide image elements
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
largeImage.src = imageURI;
}
// A button will call this function
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType: destinationType.DATA_URL
});
}
// A button will call this function
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL
});
}
// A button will call this function
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source
});
}
// Called if something bad happens.
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
<button onclick="capturePhoto();">Capture Photo</button>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
function captureSuccess(mediaFiles) {
//var i, len;
//for (i = 0, len = mediaFiles.length; i < len; i += 1) {
// //uploadFile(mediaFiles[i]);
//}
//navigator.notification.alert('Weee', null, 'Great success!');
}
// Called if something bad happens.
function captureError(error) {
//var msg = 'An error occurred during capture: ' + error.code;
//navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 2 });
}
// 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 });
}
</script>
<button onclick="captureImage();">Capture Image</button>
and here is my config.xml:
<name>yadda</name>
<description>
blabla
</description>
<author href="http://blabla.github.com"
email="blabla#gmail.com">
BlaBla
</author>
<icon src="icon.png" gap:role="default" />
<feature name="http://api.phonegap.com/1.0/geolocation"/>
<feature name="http://api.phonegap.com/1.0/network"/>
<feature name="http://api.phonegap.com/1.0/file"/>
<feature name="http://api.phonegap.com/1.0/camera"/>
<feature name="http://api.phonegap.com/1.0/media"/>
<feature name="http://api.phonegap.com/1.0/device"/>
<preference name="orientation" value="portrait" />
<preference name="webviewbounce" value="false" />
<preference name="prerendered-icon" value="true" />
<plugin name="Capture" value="CDVCapture" />
<plugin name="Camera" value="CDVCamera" />
does anyone have an idea as to what I'm doing wrong?
YES! i finally got it to work, i downgraded from phonegap 2.3.0 to 2.0.0
For anyone with the same problem here is my final code:
index.html
<script src="assets/js/cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
//var i, len;
//for (i = 0, len = mediaFiles.length; i < len; i += 1) {
// //uploadFile(mediaFiles[i]);
//}
//navigator.notification.alert('Weee', null, 'Great success!');
}
// Called if something bad happens.
//
function captureError(error) {
//var msg = 'An error occurred during capture: ' + error.code;
//navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 2 });
}
// 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 });
}
</script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); }
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
alert("device is ready");
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType: destinationType.DATA_URL
});
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL
});
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source
});
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body onLoad="onLoad()">
<button onclick="capturePhoto();">Capture Photo</button> <br><br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br><br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
<br><button onclick="captureImage();">Capture Image</button> <br>
config.xml
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
id = "com.phonegap.getting.started"
version = "1.0.0">
<name>bla</name>
<description>
bla
</description>
<author href="http://bla.github.com"
email="bla#gmail.com">
bla
</author>
<icon src="icon.png" gap:role="default" />
<feature name="http://api.phonegap.com/1.0/geolocation"/>
<feature name="http://api.phonegap.com/1.0/network"/>
<feature name="http://api.phonegap.com/1.0/file"/>
<feature name="http://api.phonegap.com/1.0/camera"/>
<feature name="http://api.phonegap.com/1.0/media"/>
<feature name="http://api.phonegap.com/1.0/device"/>
<feature name="http://api.phonegap.com/1.0/notification"/>
<feature name="http://api.phonegap.com/1.0/battery"/>
<preference name="orientation" value="portrait" />
<preference name="webviewbounce" value="false" />
<preference name="prerendered-icon" value="true" />
<preference name="phonegap-version" value="2.0.0" />
<preference name="fullscreen" value="false" />
<preference name="stay-in-webview" value="false" />
<preference name="ios-statusbarstyle" value="default" />
<preference name="android-minSdkVersion" value="7" />
<preference name="android-installLocation" value="internalOnly" />
<preference name="target-device" value="universal" />
<preference name="autohide-splashscreen" value="true" />
<preference name="load-url-timeout" value="60000" />
<preference name="show-splashscreen-spinner" value="true" />
<preference name="show-splash-screen-spinner" value="true" />
<preference name="allow-inline-media-playback" value="false" />
<preference name="launch-mode" value="standard" />
<plugin name="Capture" value="CDVCapture" />
<plugin name="Camera" value="CDVCamera" />
</widget>
THANKS! to everyone who helped :)
I dont have any experience with ios but i think better you do a simple code to open camera something like
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
If this works fine add your further code step by step.
These are preferences in using in xml
<preference name="orientation" value="landscape" />
<preference name="fullscreen" value="false" />
<preference name="phonegap-version" value="2.0.0" />
<preference name="webviewbounce" value="false" />
<preference name="stay-in-webview" value="false" />
<preference name="ios-statusbarstyle" value="default" />
<preference name="android-minSdkVersion" value="7" />
<preference name="android-installLocation" value="internalOnly" />
<preference name="prerendered-icon" value="false" />
<preference name="target-device" value="universal" />
<preference name="autohide-splashscreen" value="false" />
<preference name="load-url-timeout" value="60000" />
<preference name="show-splashscreen-spinner" value="true" />
<preference name="show-splash-screen-spinner" value="true" />
<preference name="allow-inline-media-playback" value="false" />
<preference name="launch-mode" value="standard" />
<plugin name="Camera" value="CDVCamera" />
<feature name="http://api.phonegap.com/1.0/camera"/>
<feature name="http://api.phonegap.com/1.0/file"/>
<feature name="http://api.phonegap.com/1.0/media"/>
<feature name="http://api.phonegap.com/1.0/notification"/>
<feature name="http://api.phonegap.com/1.0/battery"/>
<feature name="http://api.phonegap.com/1.0/device"/>
This may be due to mismatch between downloaded version of PhoneGap and sample code of Camera.
You can check camera sample code version on top-right bar of Phonegap.com as show in below screenshot.
Try adding a body tag to your document and something like:
<body onLoad="onLoad()">
Then add the device ready listener to the onLoad function:
function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); }
This is because you want to make sure all of the DOM elements are loaded before you check the deviceready state.