I have problem with binding the OData to the table. When i define a function in js file it says "is not a function"
odata.js
getBoM : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/ProductHeadSet('12345')/ProductHead2BOM";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getBoM (EntityBoMSet)");
xyz_homepage.xyz_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
},
Controller.js
var oProductHead2BoM = xyz_homepage.xyz_homepage.src.odata.getBoM(iNumber);
this.oModelProductHead2BoM.setData(oProductHead2BoM);
at the .getBoM(iNumber) it says, "Uncaught TypeError: xyz_homepage.xyz_homepage.src.odata.getBoM is not a function"
Edit :
controller.js
handleRouteMatched : function(oEvent) {
if (oEvent.getParameter("name") === "page") {
var iNumber = oEvent.getParameter("arguments").number;
var oDataResult = xyz_homepage.xyz_homepage.src.odata
.getDetailsProd(iNumber);
this.oModelProdManag.setData(oDataResult);
var aDocuments = xyz_homepage.xyz_homepage.src.odata.getDocumentsProd(iNumber);
this.oModelDocuments.setData(aDocuments);
//Call bom routine and set data
var oProductHead2BoM = xyz_homepage.xyz_homepage.src.odata.getProductHead2BOM(iNumber);
this.oModelProductHead2BoM.setData(oProductHead2BoM);
So when i debug and click on function ".getDocumentsProd" i can find the function which is reference to odata.js
Odata.js
getDocumentsProd Function
getDocumentsProd : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/DocumentsSet/?$filter=Material%20eq%20'" + sNumber + "'";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData.results;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getDocumentsProd (EntityDocumentsSet)");
xyz_homepage.xyz_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
},
On the same note i have for the getProductHead2BOM function.
getProductHead2BOM : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/ProductHeadSet('5199182')/ProductHead2BOM";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getProductHead2BOM (EntityProductHead2BOM)");
zplm_homepage.zplm_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
}
I could see documents Odata but not for ProductsHeadBom
Related
i have the function for offline data it means if i dnt have internet read my offline data file ! but i have exception "type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'int'"
can u show me where did i wrong in my code....! i think it comes from my for loop where i declaire var OfflineCampList
var offlineData;
var campOfflineDataNew =[];
int campaginDataFilelength =await campaignId_txt.length();
//if Dataversion change data will download for respected shelf .....................
///type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'int'
if(campaginDataFilelength != 0){
try{
final file = File(campaignId_txt.path);
var offline_JSONData = await file.readAsString();
offlineData = json.decode(offline_JSONData);
var OfflineCampList = List<OfflineCampaignShelfList>.from(offlineData["CampaignShelfList"].map((x) => OfflineCampaignShelfList.fromJson(x)));
//campaignId_txt.delete();
CampList.forEach((camp) async{
OfflineCampList.forEach((OfCamp) async {
if(camp.photographerCampaignId == OfCamp.photographerCampaignId){
if(camp.dataVersion != OfCamp.dataVersion){
Directory subCampaignsFolder = Directory(CampaignsFolder.path+camp.photographerCampaignId.toString()+"/");
subCampaignsFolder.create(recursive: true);
File PATH_photographerImageLogoPath = File(subCampaignsFolder.path+"photographerImageLogo.jpg");
File PATH_coverPhoto = File(subCampaignsFolder.path+"coverPhoto.jpg");
File PATH_shelfImagePath = File(subCampaignsFolder.path+"shelfImage.jpg");
File PATH_photographerProfilePhoto = File(subCampaignsFolder.path+"profilePhotoPhotographer.jpg");
Map<String, dynamic> autoDonw = new Map();
var IsPhotoboothUser = {'"IsPhotoboothUser"' : camp.isPhotoboothUser};
var PhotographerId = {'"PhotographerId"' : camp.photographerId};
print("IsPhotoboothUserOffline" + PhotographerId.toString());
var photographerCampaignId = {'"PhotographerCampaignId"' : camp.photographerCampaignId};
var campaignTitle = {'"CampaignTitle"' : '"'+camp.campaignTitle+'"'};
var businessName = {'"BusinessName"' : '"'+camp.businessName+'"'};
var campaignDate = {'"Date"' : '"'+camp.date+'"'};
var coverImagePath = {'"CoverImagePath"' : '"'+PATH_coverPhoto.path+'"'};
var shelfImage = {'"ShelfImagePath"' : '"'+PATH_shelfImagePath.path+'"'};
var photographerProfilePhoto = {'"PhotographerProfilePhoto"' : '"'+PATH_photographerProfilePhoto.path+'"' };
var photographerFullName = {'"PhotographerFullName"' :'"'+camp.photographerFullName+'"'};
var photographerImageLogo = {'"PhotographerImageLogo"' : '"'+PATH_photographerImageLogoPath.path+'"'};
var CampaignFlashScreenHeader = {'"CampaignFlashScreenHeader"' : '"'+camp.campaignFlashScreenHeader+'"'};
var CampaignFlashScreenGretting = {'"CampaignFlashScreenGretting"' : '"'+camp.campaignFlashScreenGretting+'"'};
var CampaignFlashScreenDescription = {'"CampaignFlashScreenDescription"' : '"'+camp.campaignFlashScreenDescription+'"'};
var IsPrimary = {'"IsPrimary"' : camp.isPrimary};
var IsShare = {'"IsShare"' : camp.isShare};
var IsComment = {'"IsComment"' : camp.isComment};
var IsFurtherInvite = {'"IsFurtherInvite"' : camp.isFurtherInvite};
var IsSelectPhotosForAlbumDesign = {'"IsSelectPhotosForAlbumDesign"' : camp.isSelectPhotosForAlbumDesign};
var IsAddPhotos = {'"IsAddPhotos"' : camp.isAddPhotos};
var IsMyself = {'"IsMyself"' : camp.isMyself};
var DataVersion = {'"DataVersion"' : camp.dataVersion};
var IsCampaignLike = {'"IsCampaignLike"' : camp.isCampaignLike};
var IsCampaignSlideShow = {'"IsCampaignSlideShow"' : camp.isCampaignSlideShow};
var IsCampaignFaceMatch = {'"IsCampaignFaceMatch"' : camp.isCampaignFaceMatch};
var isCampaignAlbumDesign = {'"isCampaignAlbumDesign"' : camp.isCampaignAlbumDesign};
var isCampaignPersonalizedPrintingOrders = {'"isCampaignPersonalizedPrintingOrders"' : camp.isCampaignPersonalizedPrintingOrders};
autoDonw.addAll(photographerCampaignId);
autoDonw.addAll(IsPhotoboothUser);
autoDonw.addAll(photographerProfilePhoto);
autoDonw.addAll(photographerFullName);
autoDonw.addAll(photographerImageLogo);
autoDonw.addAll(campaignTitle);
autoDonw.addAll(shelfImage);
autoDonw.addAll(campaignDate);
autoDonw.addAll(businessName);
autoDonw.addAll(coverImagePath);
autoDonw.addAll(CampaignFlashScreenHeader);
autoDonw.addAll(CampaignFlashScreenGretting);
autoDonw.addAll(CampaignFlashScreenDescription);
autoDonw.addAll(IsPrimary);
autoDonw.addAll(IsShare);
autoDonw.addAll(IsComment);
autoDonw.addAll(IsFurtherInvite);
autoDonw.addAll(IsSelectPhotosForAlbumDesign);
autoDonw.addAll(IsAddPhotos);
autoDonw.addAll(IsMyself);
autoDonw.addAll(DataVersion);
autoDonw.addAll(IsCampaignLike);
autoDonw.addAll(IsCampaignSlideShow);
autoDonw.addAll(IsCampaignFaceMatch);
autoDonw.addAll(isCampaignAlbumDesign);
autoDonw.addAll(PhotographerId);
autoDonw.addAll(isCampaignPersonalizedPrintingOrders);
await campOfflineDataNew.add(autoDonw);
await dio.download(camp.photographerImageLogo, PATH_photographerImageLogoPath.path);
await dio.download(camp.coverImagePath, PATH_coverPhoto.path);
await dio.download(camp.shelfImagePath, PATH_shelfImagePath.path);
await dio.download(camp.photographerProfilePhoto, PATH_photographerProfilePhoto.path);
}else{
await campOfflineDataNew.add(json.encode(OfCamp.toJson()));
}
}
});
});
await campaignId_txt.writeAsString('{ "SuccessCode": "S0019","SuccessMessage": "Success.","CampaignShelfList":'+campOfflineDataNew.toString()+"}");
return ShelfList.fromJson(json.decode(offline_JSONData));
}catch(e){
print(e);
}
}
//if Campaign data file is MISSING ... then ....
if(campaginDataFilelength == 0){
print('--------------------------');
for (final camp in CampList) {
Directory subCampaignsFolder = Directory(CampaignsFolder.path+camp.photographerCampaignId.toString()+"/");
subCampaignsFolder.create(recursive: true);
File PATH_photographerImageLogoPath = File(subCampaignsFolder.path+"photographerImageLogo.jpg");
await dio.download(camp.photographerImageLogo, PATH_photographerImageLogoPath.path);
File PATH_coverPhoto = File(subCampaignsFolder.path+"coverPhoto.jpg");
await dio.download(camp.coverImagePath, PATH_coverPhoto.path);
File PATH_shelfImagePath = File(subCampaignsFolder.path+"shelfImage.jpg");
await dio.download(camp.shelfImagePath, PATH_shelfImagePath.path);
File PATH_photographerProfilePhoto = File(subCampaignsFolder.path+"profilePhotoPhotographer.jpg");
await dio.download(camp.photographerProfilePhoto, PATH_photographerProfilePhoto.path);
//var azim = camp.businessName ?? Globals.PhotographerLOGO;
sharedPreferences.setInt("PhotographerCampaignId", camp.photographerCampaignId);
sharedPreferences.setString("PhotographerProfilePhoto", camp.photographerProfilePhoto);
sharedPreferences.setString("PhotographerFullName", camp.photographerFullName);
sharedPreferences.setString("PhotographerImageLogo", camp.photographerImageLogo);
sharedPreferences.setString("CampaignTitle", camp.campaignTitle);
Map<String, dynamic> offlineData = new Map();
var IsPhotoboothUser = {'"IsPhotoboothUser"' : camp.isPhotoboothUser};
var PhotographerId = {'"PhotographerId"' : camp.photographerId};
var photographerCampaignId = {'"PhotographerCampaignId"' : PhotographerId.toString()};
var campaignTitle = {'"CampaignTitle"' : '"'+camp.campaignTitle+'"'};
var businessName = {'"BusinessName"' : '"'+camp.businessName+'"'};
var campaignDate = {'"Date"' : '"'+camp.date+'"'};
var coverImagePath = {'"CoverImagePath"' : '"'+PATH_coverPhoto.path+'"'};
var shelfImage = {'"ShelfImagePath"' : '"'+PATH_shelfImagePath.path+'"'};
var photographerProfilePhoto = {'"PhotographerProfilePhoto"' : '"'+PATH_photographerProfilePhoto.path+'"' };
var photographerFullName = {'"PhotographerFullName"' :'"'+camp.photographerFullName+'"'};
var photographerImageLogo = {'"PhotographerImageLogo"' : '"'+PATH_photographerImageLogoPath.path+'"'};
var CampaignFlashScreenHeader = {'"CampaignFlashScreenHeader"' : '"'+camp.campaignFlashScreenHeader+'"'};
var CampaignFlashScreenGretting = {'"CampaignFlashScreenGretting"' : '"'+camp.campaignFlashScreenGretting+'"'};
var CampaignFlashScreenDescription = {'"CampaignFlashScreenDescription"' : '"'+camp.campaignFlashScreenDescription+'"'};
var IsPrimary = {'"IsPrimary"' : camp.isPrimary};
var IsShare = {'"IsShare"' : camp.isShare};
var IsComment = {'"IsComment"' : camp.isComment};
var IsFurtherInvite = {'"IsFurtherInvite"' : camp.isFurtherInvite};
var IsSelectPhotosForAlbumDesign = {'"IsSelectPhotosForAlbumDesign"' : camp.isSelectPhotosForAlbumDesign};
var IsAddPhotos = {'"IsAddPhotos"' : camp.isAddPhotos};
var IsMyself = {'"IsMyself"' : camp.isMyself};
var DataVersion = {'"DataVersion"' : camp.dataVersion};
var IsCampaignLike = {'"IsCampaignLike"' : camp.isCampaignLike};
var IsCampaignSlideShow = {'"IsCampaignSlideShow"' : camp.isCampaignSlideShow};
var IsCampaignFaceMatch = {'"IsCampaignFaceMatch"' : camp.isCampaignFaceMatch};
var isCampaignAlbumDesign = {'"isCampaignAlbumDesign"' : camp.isCampaignAlbumDesign};
print("IsPhotoboothUser :" + IsPhotoboothUser.toString());
var isCampaignPersonalizedPrintingOrders = {'"isCampaignPersonalizedPrintingOrders"' : camp.isCampaignPersonalizedPrintingOrders};
Globals.PhotoGrapher.add(camp.photographerProfilePhoto);
offlineData.addAll(photographerCampaignId);
offlineData.addAll(IsPhotoboothUser);
offlineData.addAll(photographerProfilePhoto);
offlineData.addAll(photographerFullName);
offlineData.addAll(photographerImageLogo);
offlineData.addAll(campaignTitle);
offlineData.addAll(shelfImage);
offlineData.addAll(campaignDate);
offlineData.addAll(businessName);
offlineData.addAll(coverImagePath);
offlineData.addAll(CampaignFlashScreenHeader);
offlineData.addAll(CampaignFlashScreenGretting);
offlineData.addAll(CampaignFlashScreenDescription);
offlineData.addAll(IsPrimary);
offlineData.addAll(IsShare);
offlineData.addAll(IsComment);
offlineData.addAll(IsFurtherInvite);
offlineData.addAll(IsSelectPhotosForAlbumDesign);
offlineData.addAll(IsAddPhotos);
offlineData.addAll(IsMyself);
offlineData.addAll(DataVersion);
offlineData.addAll(IsCampaignLike);
offlineData.addAll(IsCampaignSlideShow);
offlineData.addAll(IsCampaignFaceMatch);
offlineData.addAll(isCampaignAlbumDesign);
offlineData.addAll(isCampaignPersonalizedPrintingOrders);
offlineData.addAll(PhotographerId);
campgaignData.add(offlineData.toString());
campaignId_txt.writeAsString('{ "SuccessCode": "S0019","SuccessMessage": "Success.","CampaignShelfList":'+campgaignData.toString()+"}");
}
return ShelfList.fromJson(json.decode(response.body));
}
this my method where if internet is no use this
else if (snapshot.hasError) {
_futureShelf = FirstTimeOffline();
return FutureBuilder<ShelfList>(
future: _futureShelf,
builder: (BuildContext , snapshot) {
if(snapshot.hasData) {
return gridimages(
items: snapshot.data.campaignShelfList,
);
}
else{
Center(child: Text("Something Went Wrong"));
}
return Center(child: Text("offline"));
},
);
}
read file function
Future<ShelfList> FirstTimeOffline() async {
String text;
try {
final file = File(campaignId_txt.path);
text = await file.readAsString();
print("waittttt : " + text);
return ShelfList.fromJson(json.decode(text));
} catch (e) {
print("Couldn't read file"+ e);
///here i m getting exception///
}
}
here is my txt data response file
{
"SuccessCode": "S0019",
"SuccessMessage": "Success.",
"CampaignShelfList": [
{
"PhotographerCampaignId": {
"PhotographerId": 169
},
"IsPhotoboothUser": 0,
"PhotographerProfilePhoto": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/26/profilePhotoPhotographer.jpg",
"PhotographerFullName": "Pratap",
"PhotographerImageLogo": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/26/photographerImageLogo.jpg",
"CampaignTitle": "WEDDING",
"ShelfImagePath": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/26/shelfImage.jpg",
"Date": "24/04/2021",
"BusinessName": "My Businesss",
"CoverImagePath": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/26/coverPhoto.jpg",
"CampaignFlashScreenHeader": "Thank you",
"CampaignFlashScreenGretting": "Thank you",
"CampaignFlashScreenDescription": "Thank you",
"IsPrimary": 1,
"IsShare": 1,
"IsComment": 1,
"IsFurtherInvite": 1,
"IsSelectPhotosForAlbumDesign": 1,
"IsAddPhotos": 1,
"IsMyself": 0,
"DataVersion": 35,
"IsCampaignLike": 1,
"IsCampaignSlideShow": 1,
"IsCampaignFaceMatch": 1,
"isCampaignAlbumDesign": 1,
"isCampaignPersonalizedPrintingOrders": 1,
"PhotographerId": 169
},
{
"PhotographerCampaignId": {
"PhotographerId": 169
},
"IsPhotoboothUser": 0,
"PhotographerProfilePhoto": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/2/profilePhotoPhotographer.jpg",
"PhotographerFullName": "Pratap",
"PhotographerImageLogo": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/2/photographerImageLogo.jpg",
"CampaignTitle": "TESTING",
"ShelfImagePath": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/2/shelfImage.jpg",
"Date": "18/03/2021",
"BusinessName": "My Businesss",
"CoverImagePath": "/data/user/0/com.photogranth.photographer/app_flutter/Campaigns/2/coverPhoto.jpg",
"CampaignFlashScreenHeader": "Thank you",
"CampaignFlashScreenGretting": "Wishing you a lifetime of love and happiness.",
"CampaignFlashScreenDescription": "A",
"IsPrimary": 0,
"IsShare": 1,
"IsComment": 1,
"IsFurtherInvite": 0,
"IsSelectPhotosForAlbumDesign": 0,
"IsAddPhotos": 1,
"IsMyself": 0,
"DataVersion": 39,
"IsCampaignLike": 1,
"IsCampaignSlideShow": 1,
"IsCampaignFaceMatch": 0,
"isCampaignAlbumDesign": 0,
"isCampaignPersonalizedPrintingOrders": 0,
"PhotographerId": 169
}
]
}
Change this:
int campaginDataFilelength =await campaignId_txt.length()
Into this:
int campaginDataFilelength =await campaignId_txt.length
That's the first one i caught, will look for more. But code is a bit messy.
Basically, you're error is because a variable is expecting an int, but it's getting a map. Because you are using var for everything, it's harder to tell where this is failing.
Also this int campaginDataFilelength =campaignId_txt
You need to get campaign id_text then find it's length.
maybe somebody can to explain me why I can't send file, maybe needed additional script or something els?
/*
* Ajaxupload for Jeditable
*
* Copyright (c) 2008-2009 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Depends on Ajax fileupload jQuery plugin by PHPLetter guys:
* http://www.phpletter.com/Our-Projects/AjaxFileUpload/
*
* Project home:
* http://www.appelsiini.net/projects/jeditable
*
* Revision: $Id$
*
*/
$.editable.addInputType('ajaxupload', {
/* create input element */
element : function(settings) {
settings.onblur = 'ignore';
var input = $('<input type="file" id="upload" name="upload" />');
$(this).append(input);
return(input);
},
content : function(string, settings, original) {
/* do nothing */
},
plugin : function(settings, original) {
var form = this;
form.attr("enctype", "multipart/form-data");
$("button:submit", form).bind('click', function() {
//$(".message").show();
// Modification to include original id and submitdata in target's querystring
var queryString;
if ($.isFunction(settings.submitdata)) {
queryString = jQuery.param(settings.submitdata.apply(self, [self.revert, settings]));
} else {
queryString = jQuery.param(settings.submitdata);
}
if (settings.target.indexOf('?') < 0) {
queryString = '?' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
} else {
queryString = '&' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
}
settings.target += queryString;
// End modification
$.ajaxFileUpload({
url: settings.target,
secureuri:false,
// Add the following line
data : settings.submitdata,
fileElementId: 'upload',
dataType: 'html',
success: function (data, status) {
$(original).html(data);
original.editing = false;
},
error: function (data, status, e) {
alert(e);
}
});
return(false);
});
}
});
$(\".ajaxupload\").editable('/?action=upload_profile_photo', {
indicator : '<i class=\"fa fa-spinner fa-pulse\"></i>',
type : 'ajaxupload',
submit : 'Upload',
cancel : 'Cancel',
tooltip : \"Click to upload...\"
});
<p class=\"ajaxupload\" id=\"profile_photo\"><img class=\"img-thumbnail img-responsive\" src=\"http://www.in-elite.com/?action=no_image_text\" alt=\"\"></p>
how result its passed only
print_r($._GET)Array ( [action] => upload_profile_photo [id] =>
profile_photo ) print_r($._POST)Array ( [value] => 20150501_153530.jpg
[id] => profile_photo )
And question so, How to send file?
Ux I found the problem ;-)
I'm forgot to add one js file called jquery.ajaxfileupload.js
<script type=\"text/javascript\" src=\"/includes/JS/jquery.ajaxfileupload.js\" charset=\"utf-8\"></script>
And content of this jquery.ajaxfileupload.js file is
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data);
//jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
Now everything ok and file are uploaded successfully.... Just needed to modified php script for which type of the data you need to upload
Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.
Need to show a pop-up when user clicks on the line. Code as below but does not work:
var ClickLon;
var ClickLat;
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend(
{}, this.defaultHandlerOptions
);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions
);
},
trigger: function(e) {
var lonlat = map.getLonLatFromPixel(e.xy);
ClickLon = lonlat.lon;
ClickLat = lonlat.lat;
}
});
function onPopupClose(evt) {
selectControl.unselect(selectedFeature);
}
function onFeatureSelect(feature) {
selectedFeature = feature;
id = feature.id;
alert(ClickLon);
var lonLat = new OpenLayers.LonLat(ClickLon, ClickLat).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
popup = new OpenLayers.Popup.FramedCloud("chicken",
lonLat,
null,
"<div style='font-size:.8em'>" +CableLineText_arr[id] +"</div>",
null, true, onPopupClose);
feature.popup = popup;
map.addPopup(popup);
}
function onFeatureUnselect(feature) {
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
...
var lineLayer = new OpenLayers.Layer.Vector("Line Layer");
map.addLayer(lineLayer);
map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));
var click = new OpenLayers.Control.Click();
map.addControl(click);
click.activate();
selectControl = new OpenLayers.Control.SelectFeature(lineLayer,
{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
drawControls = {
polygon: new OpenLayers.Control.DrawFeature(lineLayer,
OpenLayers.Handler.Polygon),
select: selectControl
};
for(var key in drawControls) {
map.addControl(drawControls[key]);
}
Map projection is EPSG:4326.
Line drawing as:
var points = new Array(
new OpenLayers.Geometry.Point(47, 32.24),
new OpenLayers.Geometry.Point(45, 33),
new OpenLayers.Geometry.Point(49, 35)
);
var line = new OpenLayers.Geometry.LineString(points);
line.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
var style = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWidth: 5
};
var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
alert(lineFeature.id);
lineLayer.addFeatures([lineFeature]);
Trying to combine these two examples: http://openlayers.org/dev/examples/select-feature-openpopup.html and http://openlayers.org/dev/examples/click.html
I do not see the place where you activate your control.SelectFeature.
I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}
You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.
You can add your success notifing code in each of the $.ajax success handlers.