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>
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 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.
I managed to get the captions by foreach loop but now I'm facing a new problem.
I get duplicates in my database because of the nested loop, please check the code below.
JavaScript
window.onload = function () {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("galleryFilesAdd");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail img-responsive' alt='" + picFile.name + "' + height='220' width='300'; src='" + picFile.result + "'" +
"title='" + picFile.name + "'/><button type='button' class='delete btn btn-default' class='remove_pic'> <span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button><input type='text' id ='imagecaption[]' name='imagecaption[]' class='form-control' placeholder='Add Image Caption'>"
output.insertBefore(div, null);
div.children[1].addEventListener("click", function (event) {
div.parentNode.removeChild(div);
});
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else {
console.log("Your browser does not support File API");
}
}
Controller
public async Task<ActionResult> AddHotel(HotelViewModels.AddHotel viewModel, IEnumerable<HttpPostedFileBase> galleryFilesAdd)
{
try
{
if (ModelState.IsValid)
{
foreach (var files in galleryFilesAdd)
{
var fileName = Guid.NewGuid().ToString("N");
var extension = Path.GetExtension(files.FileName).ToLower();
string thumbpath, imagepath = "";
using (var img = Image.FromStream(files.InputStream))
{
foreach (var caption in viewModel.imagecaption)
{
var galleryImg = new hotel_gallery_image
{
hotel_id = hotel.id,
thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
entry_datetime = DateTime.Now,
guid = Guid.NewGuid().ToString("N"),
enabled = true,
image_caption = caption
};
db.hotel_gallery_image.Add(galleryImg);
}
}
}
await db.SaveChangesAsync();
return RedirectToAction("Index", "Hotel");
}
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
viewModel.Country = await db.countries.ToListAsync();
return View(viewModel);
}
and viewModel
public string[] imagecaption { get; set; }
Inserted data into database
I think the problem is in your
image_caption = viewModel.imagecaption
because you iterate through var files in galleryFilesAddyou use the reference to the same image_caption from viewModel on each iteration, so you need to filter your image_caption depending on another data (fileName or another data which you viewmodel contains).
UPDATE
Ideally if you have same properties in your ViewModel and files(filename for example), then you could do something like thatimage_caption = viewModel.FirstOrDefault(x=>x.Filename == filename).imagecaption
In order to be more specific would be helpful if you provide code for your Viemodel and galleryFilesAdd classes.
UPDATE 2
In your case 2nd foreach you iterate through whole collection of imagecaption array, on each iteration through galleryFilesAdd collection, which cause double data in you database.
If you can take your captions sequentially for the 1st file take the 1st element from imagecaption array and so on then you can use code like this:
if (ModelState.IsValid)
{
int index = 0;
foreach (var files in galleryFilesAdd)
{
var fileName = Guid.NewGuid().ToString("N");
var extension = Path.GetExtension(files.FileName).ToLower();
string thumbpath, imagepath = "";
using (var img = Image.FromStream(files.InputStream))
{
if(index < viewModel.imagecaption.Length){
var galleryImg = new hotel_gallery_image
{
hotel_id = hotel.id,
thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
entry_datetime = DateTime.Now,
guid = Guid.NewGuid().ToString("N"),
enabled = true,
image_caption = viewModel.imagecaption[index]
};
db.hotel_gallery_image.Add(galleryImg);
index++;
}
}
}
I'd like to give the user the option to upload a file, but it's not strictly necessary. This script seems to glitch if there is no file specified. How can I fix that? It seems like the line it really doesn't like is: var file1 = folder.createFile(blob1);
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1]);
return "Your entry was successfully uploaded!";
} catch (error) {
return error.toString();
}
}
EDIT: Thanks to suggestion, here is what I ended up with (allows for three optional files)
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
var blob2 = form.myFile2;
var blob3 = form.myFile3;
// check for empty blobs on file attachment uploads
if( !isEmpty(blob1) ) {
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
} else {
var f1 = "nada";
}
if( !isEmpty(blob2) ) {
var file2 = folder.createFile(blob2);
file2.setDescription("Uploaded by " + form.myName);
var f2 = '=HYPERLINK("' + file2.getUrl() + '", "File 2")';
} else {
var f2 = "nada";
}
if( !isEmpty(blob3) ) {
var file3 = folder.createFile(blob3);
file3.setDescription("Uploaded by " + form.myName);
var f3 = '=HYPERLINK("' + file3.getUrl() + '", "File 3")';
} else {
var f3 = "nada";
}
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1, f2, f3]);
return "Your entry was successfully uploaded!";
} catch (error) {
return error.toString();
}
}
// New stuff. A function that tests if a string is empty or null
function isEmpty(str) {
return (!str || 0 === str.length);
}
Can't you just test if a name is specified? I.e. add an if statement that checks that the name is not null and not empty... You might also want to test for things like slashes, in case the user is trying to create subdirectories...
I lifted a test for null or empty from here, but you can roll your own.
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var id = "1L2syfAOm6MiYPtWuWwFZFK_ZtLpLOjNx9EpjHh2IKUY";
var ss = SpreadsheetApp.openById(id);
var blob1 = form.myFile1;
if( !isEmpty(blob1) ) {
var file1 = folder.createFile(blob1);
file1.setDescription("Uploaded by " + form.myName);
var f1 = '=HYPERLINK("' + file1.getUrl() + '", "File 1")';
Logger.log("test");
var sheet = ss.getSheetByName('Sheet1');
sheet.appendRow([form.myName, form.addy, form.twitter, form.status, form.what, form.projTitle,
form.brief, form.full, form.role, form.date, form.website, f1]);
return "Your entry was successfully uploaded!";
} else {
return "No file name specified!";
}
} catch (error) {
return error.toString();
}
}
// New stuff. A function that tests if a string is empty or null
function isEmpty(str) {
return (!str || 0 === str.length);
}
Just check if blob1 is null, if it is then trhow an exception.
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.