I trying to make simple sharepoint app on javascript.
I create list, named "test" and add some records where.
After starting my app i get error: "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested".
It raised in success function.
Here is code:
'use strict';
var web;
var hostweburl;
var appweburl;
var collListItem;
function sharePointReady() {
hostweburl =
decodeURIComponent(
getQueryStringParameter('SPHostUrl')
);
appweburl =
decodeURIComponent(
getQueryStringParameter('SPAppWebUrl')
);
var scriptbase = hostweburl + '/_layouts/15/';
$.getScript(scriptbase + 'SP.js', function () {
$.getScript(scriptbase + 'SP.Runtime.js', function () {
$.getScript(scriptbase + 'SP.RequestExecutor.js', printAllListNamesFromHostWeb).fail(function () { alert("fail") });
}).fail(function () { alert("fail") });
}).fail(function () { alert("fail") });
//ExecuteOrDelayUntilScriptLoaded(printAllListNamesFromHostWeb, "SP.js");
//printAllListNamesFromHostWeb();
}
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
function printAllListNamesFromHostWeb() {
var context;
var factory;
var appContextSite;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
var oList = web.get_lists().getByTitle("testList");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>10</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Id, Title)');
context.executeQueryAsync(
//Function.createDelegate(this, success),
//Function.createDelegate(this, errorHandler)
success, errorHandler
);
}
function success(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() + '\nTitle: ' + oListItem.get_item('Title');
}
alert(listItemInfo.toString());
}
function errorHandler(sender, args) {
alert('Fail: ' + args.get_message() + '\n' + args.get_stackTrace());
}
sharePointReady();
var listItemEnumerator = collListItem.getEnumerator();
above line in success function may be causing this issue.
You have declared collListItem variable in printAllListNamesFromHostWeb function. So it will not available/will be undefined in success function.
What you need to do is declare collListItem variable global (i.e. outside of your printAllListNamesFromHostWeb function where you have declared appweburl,hostweburl,web variables) and your code will work fine.
Related
When I run this code it generates the appropriate file upload ui and adds the event listener to the upload button. However the first line in the upload function throws an error - Cannot read property 'style' of undefined - for this.missingFile. What am I doing wrong here?
function FileUploader(props) {
var div = document.querySelector(props.element);
var uid = generateGuid();
var templateHtml = "<p><div id=\"dvMissingFile-" + uid + "\" class=\"missing-file\"> Please choose a file.</div><input type=\"file\" id=\"flUploadedFile-" + uid + "\" name=\"flUploadedFile-" + uid + "\"/></p><div class=\"dvProgressBar\" id=\"progress-" + uid + "\"><div></div></div>";
div.innerHTML = templateHtml;
this.uploadButton = document.querySelector(props.uploadButton);
this.fileInput = document.querySelector("#flUploadedFile-" + uid);
this.missingFile = document.querySelector("#dvMissingFile-" + uid);
this.progress = document.querySelector("#progress-" + uid);
this.url = props.postUrl;
this.upload = function() {
this.missingFile.style.display = "none";
if (this.fileInput.files.length === 0) {
this.missingFile.style.display = "";
}
else {
var file = this.fileInput.files[0];
var xhr = new XMLHttpRequest();
var pbar = document.querySelector("#progress-" + uid + ">div");
if (xhr.upload) {
// do upload
}
}
}
this.uploadButton.addEventListener("click", this.upload);
}
Usage example
<div id="dvUploader"></div>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>
<script>
var uploader = new FileUploader({
element: "#dvUploader",
uploadButton: "#btnUpload",
postUrl: "myposturl"
});
</script>
One small update to your code can help:
this.upload = function() {
// ...
}.bind(this);
I have a conceptual issue about scopes on the following code.
The code is a simple client-side validation script for two forms.
I used a self-invoking function to try a something different approach by avoiding to set all global variables but its behavior seems a bit weird to me.
I am still learning to code with JavaScript and I'm not an expert, but these advanced features are a bit complicated.
I don't want to use jQuery but only pure JavaScript in order to learn the basis.
<!-- Forms handling -->
<script src="validate_functions.js"></script>
<script>
(function main() {
var frmPrev = document.getElementById('frmPrev');
var frmCont = document.getElementById('frmCont');
var btnPrev = frmPrev['btnPrev'];
var btnCont = frmCont['btnCont'];
var caller = '';
var forename = '';
var surname = '';
var phone = '';
var email = '';
var privacy = '';
var message = '';
var infoBox = document.getElementById('info-box');
var infoBoxClose = infoBox.getElementsByTagName('div')['btnClose'];
btnPrev.onclick = function(e) {
submit(e);
};
btnCont.onclick = function(e) {
submit(e);
};
function submit(which) {
caller = which.target.name;
var errors = '';
if(caller == 'btnPrev') {
forename = frmPrev['name'].value.trim();
surname = frmPrev['surname'].value.trim();
phone = frmPrev['phone'].value.trim();
email = frmPrev['email'].value.trim();
message = frmPrev['message'].value.trim();
privacy = frmPrev['privacy'].checked;
}
if(caller == 'btnCont') {
phone = frmCont['phone'].value.trim();
email = frmCont['email'].value.trim();
message = frmCont['message'].value.trim();
}
errors = validateFields(caller, forename, surname, phone, email, privacy, message);
if(errors == '') {
var params = 'which=' + caller;
params += '&fname=' + forename;
params += '&sname=' + surname;
params += '&tel=' + phone;
params += '&email=' + email;
params += '&priv=' + privacy;
params += '&mess=' + message;
var request = asyncRequest();
request.open('POST', "send-mail.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Content-length', params.length);
request.setRequestHeader('Connection', 'close');
request.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText != null) {
infoBox.innerHTML = this.responseText;
} else {
infoBox.innerHTML = '<p>No data from server!</p>';
}
} else {
infoBox.innerHTML = '<p>Could not connect to server! (error: ' + this.statusText + ' )</p>';
}
}
}
request.send(params);
} else {
infoBox.innerHTML = errors;
}
infoBox.style.display = 'block';
}
infoBoxClose.onclick = function() {
infoBox.style.display = 'none';
infoBox.innerHTML = '';
};
function validateFields(_caller, _forename, _surname, _phone, _email, _privacy, _message) {
var errs = '';
if(_caller == 'btnPrev') {
errs += validateForename(_forename);
errs += validateSurname(_surname);
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
errs += validatePrivacy(_privacy);
}
if(_caller == "btnCont") {
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
}
return errs;
}
function asyncRequest() {
var request;
try {
request = new XMLHttpRequest();
}
catch(e1) {
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3) {
request = null;
}
}
}
return request;
}
})();
Web console keeps telling me that single validate functions are not defined.
Why?
They should be loaded from the external script.. furthermore they should have a global scope.
Thank you in advance :)
Problem solved!
The path to the external script was incorrect.
Sorry for this rubbish! ^^"
Each section of my code below creates a new handlebars.js template to call the "User Behance API". As you can see, each section has similar code, with a variable or two difference.
Is there a way to clean up this code, and combine these separate functions into one? Just seems like a lot of code, but then again I am new to handlebars.
// BEHANCE API INFO ---
var apiKey = 'ZLBxK9rEfHwJf9K0rmseNr2fS2gS2HJW';
var userID = 'creativemints';
var perPage = 10;
var behanceUserAPI = 'http://www.behance.net/v2/users/' + userID + '?callback=?&api_key=' + apiKey;
var behanceProjectAPI = 'http://www.behance.net/v2/users/' + userID + '/projects?callback=?&api_key=' + apiKey + '&per_page=' + perPage;
// BEHANCE - USER HEADER ---
(function () {
function setUserTemplate() {
var userData = JSON.parse(sessionStorage.getItem('behanceUser')),
getTemplate = $('#userHead').html(),
template = Handlebars.compile(getTemplate),
result = template(userData);
$('header').html(result);
}
if (sessionStorage.getItem('behanceUser')) {
setUserTemplate();
} else {
$.getJSON(behanceUserAPI, function (user) {
var data = JSON.stringify(user);
sessionStorage.setItem('behanceUser', data);
setUserTemplate();
});
}
})();
// BEHANCE - USER ABOUT ---
(function () {
function setUserTemplate() {
var userData = JSON.parse(sessionStorage.getItem('behanceUser')),
getTemplate = $('#userAbout').html(),
template = Handlebars.compile(getTemplate),
result = template(userData);
$('.about').html(result);
}
if (sessionStorage.getItem('behanceUser')) {
setUserTemplate();
} else {
$.getJSON(behanceUserAPI, function (user) {
var data = JSON.stringify(user);
sessionStorage.setItem('behanceUser', data);
setUserTemplate();
});
}
})();
// BEHANCE - USER FOOTER ---
(function () {
function setUserTemplate() {
var userData = JSON.parse(sessionStorage.getItem('behanceUser')),
getTemplate = $('#userFoot').html(),
template = Handlebars.compile(getTemplate),
result = template(userData);
$('footer').html(result);
}
if (sessionStorage.getItem('behanceUser')) {
setUserTemplate();
} else {
$.getJSON(behanceUserAPI, function (user) {
var data = JSON.stringify(user);
sessionStorage.setItem('behanceUser', data);
setUserTemplate();
});
}
})();
// BEHANCE - USER COPYRIGHT ---
(function () {
function setUserTemplate() {
var userData = JSON.parse(sessionStorage.getItem('behanceUser')),
getTemplate = $('#userCopyright').html(),
template = Handlebars.compile(getTemplate),
result = template(userData);
$('#copyright').html(result);
}
if (sessionStorage.getItem('behanceUser')) {
setUserTemplate();
} else {
$.getJSON(behanceUserAPI, function (user) {
var data = JSON.stringify(user);
sessionStorage.setItem('behanceUser', data);
setUserTemplate();
});
}
})();
Haven't tested this but you should be able to simply the code to something similar to this
// BEHANCE API INFO ---
var apiKey = 'ZLBxK9rEfHwJf9K0rmseNr2fS2gS2HJW';
var userID = 'creativemints';
var perPage = 10;
var behanceUserAPI = 'http://www.behance.net/v2/users/' + userID + '?callback=?&api_key=' + apiKey;
var behanceProjectAPI = 'http://www.behance.net/v2/users/' + userID + '/projects?callback=?&api_key=' + apiKey + '&per_page=' + perPage;
// BEHANCE - USER HEADER ---
(function () {
function setUserTemplate(templateSelector, htmlSelector) {
var userData = JSON.parse(sessionStorage.getItem('behanceUser')),
getTemplate = $(templateSelector).html(),
template = Handlebars.compile(getTemplate),
result = template(userData);
$(htmlSelector).html(result);
}
if (!sessionStorage.getItem('behanceUser')) {
$.getJSON(behanceUserAPI, function (user) {
var data = JSON.stringify(user);
sessionStorage.setItem('behanceUser', data);
});
}
setUserTemplate('#userHead','header');
setUserTemplate('#userAbout','.about');
setUserTemplate('#userFoot','footer');
setUserTemplate('#userCopyright','#copyright');
})();
I want to access files in a particular document set in a document library .
So far i was able to get the particular document set name and ID using JSOM as below .
How to read all the files inside the document set
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js");
function MainFunction() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Planner Session');
var camlQuery = new SP.CamlQuery(); //initiate the query object
camlQuery.set_viewXml('<View><Query><Where><Lt><FieldRef Name="ID" /><Value Type="Counter">3</Value></Lt></Where><OrderBy><FieldRef Name="ID" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded(sender, args) {
var DocSet = "";
var listItemEnum = collListItem.getEnumerator();
while (listItemEnum.moveNext()) {
var oListItem = listItemEnum.get_current();
DocSet += '\n\nID: ' + oListItem.get_id() + '\nName: ' + oListItem.get_item('FileLeafRef');
}
// Here i would like to get the file inside the documentSet
alert(DocSet.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
</script>
<input type="button" value="Get Products" onclick="MainFunction()"/>
How to get files of Document Set via SharePoint CSOM
Assume the following structure:
Documents (library)
|
2013 (Document set)
Query based approach
The following example demonstrates how to return Files located in Document Set using CAML query:
function getListItems(listTitle,folderUrl,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var qry = SP.CamlQuery.createAllItemsQuery();
qry.set_folderServerRelativeUrl(folderUrl);
var items = list.getItems(qry);
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(
function() {
success(items);
},
error);
}
Key points:
SP.CamlQuery.folderServerRelativeUrl property is used to return
only files located under specific url
Usage
var listTitle = 'Documents';
var docSetUrl = '/Documents/2013';
getListItems(listTitle,docSetUrl,
function(items){
for(var i = 0; i < items.get_count();i++) {
var file = items.get_item(i).get_file();
console.log(file.get_title());
}
},
function logError(sender,args)
{
console.log(args.get_message());
});
Using SP.Web.getFolderByServerRelativeUrl method
Use SP.Web.getFolderByServerRelativeUrl Method to get Document Set object located at the specified server-relative URL and then SP.Folder.files property to gets the collection of all files contained in the Document Set
Complete example:
function getFiles(folderUrl,success,error)
{
var ctx = SP.ClientContext.get_current();
var files = ctx.get_web().getFolderByServerRelativeUrl(folderUrl).get_files();
ctx.load(files);
ctx.executeQueryAsync(
function() {
success(files);
},
error);
}
Usage
var docSetUrl = '/Documents/2013'; //<-- '2013'
getFiles(docSetUrl,
function(files){
for(var i = 0; i < files.get_count();i++) {
var file = files.get_item(i);
console.log(file.get_title());
}
},
function logError(sender,args)
{
console.log(args.get_message());
});
Please find the complete code which does the following
1. Gets the required docset based on my conditions
2. gets all the files in that particular document set by checking the value in the custom column
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js");
function MainFunction() {
var currentListID = getQueryStringValue("List");
var clientContext = new SP.ClientContext.get_current();
this.ListId = "{" + currentListID + "}";
var oList = clientContext.get_web().get_lists().getById(ListId);
var camlQuery = new SP.CamlQuery(); //initiate the query object
var currentDocSetID = getQueryStringValue("ID");
camlQuery.set_viewXml('<View><Query><Where><Lt><FieldRef Name="ID" /><Value Type="Counter">' + currentDocSetID + '</Value></Lt></Where><OrderBy><FieldRef Name="ID" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded(sender, args) {
var DocSet = "";
var listItemEnum = collListItem.getEnumerator();
while (listItemEnum.moveNext()) {
var oListItem = listItemEnum.get_current();
DocSet += oListItem.get_item('FileLeafRef');
}
// Here i would like to get the file inside the documentSet
// alert(DocSet.toString());
var fsoType = oListItem.get_fileSystemObjectType();
if(oListItem.FileSystemObjectType == SP.FileSystemObjectType.Folder)
{
//var folderUrl = "/" + listName + "/" + DocSet.toString();
var RawFolderUrl = getQueryStringValue("RootFolder");
var pos = RawFolderUrl.lastIndexOf('/');
var folderUrl = RawFolderUrl.substring(0,pos) + "/" + DocSet.toString();
GetFilesFromFolder(folderUrl);
}
}
var allItems;
function GetFilesFromFolder(folderUrl)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getById(ListId);
// Use createAllItemsQuery to get items inside subfolders as well. Otherwise use new SP.CamlQuery() to get items from a single folder only
var query = SP.CamlQuery.createAllItemsQuery();
query.set_folderServerRelativeUrl(folderUrl);
allItems = list.getItems(query);
context.load(allItems, 'Include(File, FileSystemObjectType,Document_x0020_Type,Title)');
context.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFailure));
}
function OnSuccess()
{
var listItemEnumerator = allItems.getEnumerator();
while(listItemEnumerator.moveNext())
{
var currentItem = listItemEnumerator.get_current();
if(currentItem.get_fileSystemObjectType() == "0")
{
var file = currentItem.get_file();
if(file != null && currentItem.get_item("Document_x0020_Type") == "03. Minutes")
{
// alert('File Name: ' + file.get_name() + '\n' + 'File Url: ' + file.get_serverRelativeUrl());
// alert(currentItem.get_item("Title"));
var link = document.getElementById("prvMinutes");
link.href= file.get_serverRelativeUrl();
// link.innerHTML = currentItem.get_item("Title");
link.innerHTML = file.get_name();
}
}
}
}
function OnFailure(sender, args) {
alert("Failed. Message:" + args.get_message());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
function getQueryStringValue (key) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace
(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
</script>
<a id="prvMinutes" href="#" target="_blank"> </a>
I am developing android app using phonegap 1.5.0
App stores data in local database and synchronizes using web services.
I am using one button click to call synchronize data JavaScript function.
What I have found is:
This synch button's on click event fires twice.
Single record is getting uploaded twice and the uploaded time is same in the server database.
How to avoid this?
Thanks
EDIT:
Hey everyone, sorry for the delay in reply; was bit busy with some priority work.
Calling SyncData() function on click of button.
Here is the code:
document.addEventListener("DOMContentLoaded", onDeviceReady, false);
var db;
var maxrecords = 0;
var recordsprocessed = 0;
var urlstart = "http://www.mywebsite.com/";
function onDeviceReady() {
db = window.openDatabase("LocalDB", "1.0", "PhoneGap Demo", 50 * 1024 * 1024);
}
function SyncData() {
maxrecords = 0;
recordsprocessed = 0;
db.transaction(queryDB, errorCB, successCB);
}
function queryDB(tx) {
var entriestoupload = 0;
var profimagetoupload = 0;
//check how many entries are to be synchronized
tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsUploaded=0', [], function(tx, results) {
entriestoupload = parseInt(results.rows.item(0)['cnt']);
//check how many profile images are to be uploaded
tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsProfileImageUploaded=0', [], function(tx, results) {
profimagetoupload = parseInt(results.rows.item(0)['cnt']);
//synch proceeds if there is any record which is not sychronised
if (entriestoupload > 0 || profimagetoupload > 0) {
var dataMsg = '';
var porofimgMsg = '';
if (entriestoupload > 0) dataMsg = entriestoupload + ' entry, ';
if (profimagetoupload > 0) porofimgMsg = profimagetoupload + ' profile image ';
// give user exact info about what will be synchronized
if (confirm(dataMsg + porofimgMsg + ' are not synchronized.\n Do you want to start synchronisation? \n Please wait till synch successfull message appears.')) {
//start synchronisation
tx.executeSql('SELECT * FROM tblEntries ORDER BY DateOfRegistration DESC', [], uploadData, errorCB);
}
} else {
alert('All records are already Synchronized.');
}
}, errorCB);
}, errorCB);
}
function uploadData(tx, results) {
var len = results.rows.length;
maxrecords = len;
var Synched = 0;
if (len > 0) {
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
var LocalId = row['LocalId'];
var DateOfRegistration = getDateTimeformatMySql(String(row['DateOfRegistration']));
var DateOption = getDateTimeformatMySql(String(row['DateOption']));
var VolunteerId = row['VolunteerId'];
var IsUploaded = row['IsUploaded'];
var LiveId = row['LiveId'];
var ProfileImagePath = row['ProfileImagePath'];
var IsProfileImageUploaded = parseInt(row['IsProfileImageUploaded']);
var params = null;
var weburl = null;
if (IsUploaded == 0) {
//set parameters for web service
params = "LocalId=" + LocalId + "&OrganizationName=" + row['OrganizationName'] + "&FirstName=" + row['FirstName'] + "&LastName=" + row['LastName'] + "&EmailAddress=" + row['EmailAddress'] + "&MobileNumber=" + row['MobileNumber'] + "&Country=" + row['Country'] + "&State=" + row['State'] + "&City=" + row['City'] + "&Lattitude=" + row['Lattitude'] + "&Longitude=" + row['Longitude'] + "&Website=" + row['Website'] + "&DateOption=" + DateOption + "&TimeOption=" + row['TimeOption'] + "&NumberOption=" + row['NumberOption'] + +"&RadioOption=" + row['RadioOption'] + "&Details=" + row['Details'] + "&CheckBoxoption=" + row['CheckBoxoption'] + "&DropDownOption=" + row['DropDownOption'] + "&DateOfRegistration=" + DateOfRegistration + "&VolunteerId=" + VolunteerId;
//web service url
weburl = urlstart + "mywebserviceurl";
try {
$.ajax({
async: false,
type: "POST",
url: weburl,
data: params,
dataType: "json",
success: function(data, textStatus, jqXHR) {
if (data.Success == "0") {
alert('web services error:\n' + data.Message);
}
if (data.Success == "1") {
try {
LiveId = parseInt(String(data.LiveId));
IsUploaded = 1;
//Update local database to set IsUploaded and LiveId
tx.executeSql("UPDATE tblEntries SET LiveId= " + LiveId + " ,IsUploaded=1 WHERE LocalId= " + LocalId, [], function(tx, results) {
Synched = Synched + 1; /*alert(LiveId);*/
}, errorCB);
//check if profile image exists or not
if (ProfileImagePath != undefined) {
uploadImage(LiveId, LocalId, ProfileImagePath, '1', '');
}
} catch (e) {
}
}
},
error: function() {
alert("There was an error loading the feed");
}
});
} catch (e) {
}
} else {
//check if data is uploaded and image is not uploaded
if (IsProfileImageUploaded == 0 && ProfileImagePath != undefined) {
uploadImage(LiveId, ShopId, ProfileImagePath, '1', '');
}
}
}
}
} // end of querySucess function
//function to upload image
function uploadImage(LiveId, LocalId, ImagePath, UploadType, CreationDate) {
try {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = ImagePath;
options.mimeType = "image/jpg";
var params = new Object();
params.LiveId = LiveId;
params.LocalId = LocalId;
params.UploadType = UploadType;
params.CreationDate = CreationDate;
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
var url = urlstart + "mywebservice_url_to_uploadimage";
ft.upload(ImagePath, url, win, fail, options, false);
} catch (e) {
console.error("Survey App Err :" + e.message);
}
}
function win(r) {
var jsonresponse = r.response.substring(r.response.indexOf('{'), r.response.indexOf('}') + 1);
var obj = $.parseJSON(jsonresponse);
if (obj.Success == "1") {
var LocalId = parseInt(obj.LocalId);
var UploadType = parseInt(obj.UploadType);
if (UploadType == 1) {
db.transaction(function(tx) {
tx.executeSql("UPDATE tblEntries SET IsProfileImageUploaded=1 WHERE LocalId=?", [LocalId], function(tx, results) {
}, errorCB);
}, errorCB, successCB);
}
}
}
function fail(error) {
alert("There was an error uploading image");
}
Only solution i found for this is to use tap instead of click and it will solve the problem.