Javascript/Jquery:
specialInsDialog.dialog('open');
specialInsDialog.find('#buttonSave').live('click', function () {
function addSpecialInstuction(spinstructionVal, isYesVal) {
$.ajax({
type: "POST",
url: "/Portal/AddSpecialInstuction",
dataType: 'json',
data: { providerKey: selProviderKey, ownerKey: selOwnerKey, petKey: selPetKey, instruction: spinstructionVal, isPermenant: isYesVal, invoiceId: selInvoiceId },
success: function (data) {
alert('sam');
}
});
}
var chkBox = document.getElementById('checkboxSpecialIns');
if (chkBox.checked) {
var oTable = document.getElementById('table');
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
var isYes = oCells[1].childNodes[0].checked;
var spinstruction = oCells[2].childNodes[0].value;
if (typeof (spinstruction) != 'undefined' && spinstruction != '') {
addSpecialInstuction(spinstruction, isYes);
}
}
}
});
Controller :
[HttpPost]
public JsonResult AddSpecialInstuction(string providerKey, string ownerKey, string petKey, string instruction, bool isPermenant, string invoiceId)
{
char[] delimiter = {'+'};
string[] petKeys = petKey.Split(delimiter);
Pet pet = null;
foreach (var key in petKeys)
{
pet = BasicRepository.GetPet(ownerKey, key);
if (pet.SpecialInstructions != null && pet.SpecialInstructions.Where(a => a.Instruction.Trim() == instruction.Trim()).Count() <= 0)
{
pet.AddSpecialInstruction(new SpecialInstruction()
{
Instruction = instruction,
IsPermenant = isPermenant,
PetId = pet.Id,
InvoiceId = isPermenant ? Guid.Empty : Guid.Parse(invoiceId)
});
BasicRepository.Save();
}
}
Confirm("Your Special Instruction has been added.");
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}
I am having above kind of code and addSpecialInstuction method only fires when I do run the code by using firebug.Without firebug controller Action method doesn't fire.
Note: Above ajax method is inside the jquery UI popup
So Why is that ?
Related
I am using Autocomlete to show the list of location which come from database. User get the list as expected. but instate selecting from list user just click on the tab button and control going to next button. I want to avoid TAB operation here.Any suggestion how i will do that .
Here is my function :
$(document).ready(function () {
src = 'LocationHandler.ashx';
$('#txtLocationName').autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term,
type: $("#ddlDivision1").val()
},
success: function (data) {
Object.keys = Object.keys || function (o, k, r) { r = []; for (k in o) r.hasOwnProperty.call(o, k) && r.push(k); return r }
if (Object.keys(data).length == 0) {
$('#txtLocationName').val('');
alert('Location must be selected from the options.');
}
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
My Handler class looks like
public class LocationHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string term = context.Request["term"] ?? "";
string type = context.Request["type"] ?? "";
// type = "FM";
List<string> listLocationNames = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["EGLFormsDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spIARLocationNames", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#locType",
Value = type
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listLocationNames.Add(rdr["Name"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(listLocationNames));
}
public bool IsReusable
{
get
{
return false;
}
}
}
this is how i solve this.
$("#txtLocationName").keydown(function (evt) {
var keyCode = evt.keyCode || evt.which;
if (keyCode == 9) {
//evt.preventDefault();
//alert("TAB not allowed111111. Please select business unit number or name from Search box. ");
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
if (evt.key === "Tab")
{
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
});
I have a function for returning a feed which is retrieved by an AJAX-Call and now want to do something after a few of these asynchron requests have been done.
doit() is the function I call at first.
I am sorry for not providing a url, but it is an internal server.
Here is my code:
function grabFollowedCommunityPageFeed(page, cCallback) {
$.ajax({
url: "blabla.com&page=" + page,
method: "GET",
contentType: "application/atom+xml"
}).always(function(xhr, ignore, thrownMessage) {
var totalResults = 0;
if ((200 === thrownMessage.status) && (xhr)) {
totalResults = parseInt($(xhr).find("totalResults").first().text()) || -1;
}
if (cCallback && $.isFunction(cCallback)) {
cCallback({feed: xhr, resultCount: totalResults});
}
});
}
function grabFollowedCommunitiesFeeds(pagecount) {
var i = 1,
deferredArr = [];
for (i = 1; i < pagecount; i += 1) {
grabFollowedCommunityPageFeed(i, function callback(resultObj) {
deferredArr[i] = new $.Deferred();
deferredArr[i].resolve(resultObj);
});
}
return deferredArr;
}
function doit() {
var allCommunityFeedObjects = [],
allCommunityFeedObjectsCount = 0,
deferredObj = [];
(function initialReadFollowedCommunityFeedPages() {
grabFollowedCommunityPageFeed(1, function(requestObj) {
allCommunityFeedObjectsCount = requestObj.resultCount;
var tEntries = $(requestObj.communityFeed).find("entry"),
el$;
$.each(tEntries, function(ignore, el) {
el$ = $(el);
if (!($.inArray(el$, allCommunityFeedObjects) !== -1)) {
allCommunityFeedObjects.push(el$);
}
});
deferredObj = grabFollowedCommunitiesFeeds(allCommunityFeedObjectsCount) || [];
$.whenAll.apply($, deferredObj).always(function(allCommunityFeeds) {
var k = allCommunityFeeds;
// union k with allCommunityFeedObjects
});
});
})();
}
This line seems to be fine as well and I have checked it:
deferredArr[i].resolve(resultObj);
The problem is that allCommunityFeeds parameter is undefined in
$.whenAll.apply($, deferredObj).always(function(allCommunityFeeds)
and that means there is something wrong. Can you help me?
I'm using ActionHero in node.js and Angular.js.
I am trying images send to ActionHero using $http method.
but I don't know How many images are made.
so I can't define the parameter names on action in ActionHero.
below is my source.
First. images are in object, so I change object to each parameter.
insert: function (param, next) {
var url = settings.apiUrl + "/api/online/productAdd";
var vdata = {
img_objects :param.img_objects
};
angular.forEach(param.img_objects, function (v, k) {
vdata['img_file'+(k)] = v.files;
});
commonSVC.sendUrlFile("POST", url, vdata, function (state, data) {
next(state, data);
});
}
Second. make formData in sendUrlFile like source below. and then send to actionHero.
var promise = $http({
method: method,
url: url,
headers: {
'Content-Type': undefined
},
data: params,
transformRequest: function (data) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
if(angular.isObject(value)){
if(value.lastModified > 0 && value.size > 0){
formData.append(key, value);
}else{
formData.append(key, JSON.stringify(value));
}
}else{
formData.append(key, value);
}
});
return formData;
}
});
Third. ActionHero is received. but parameter isn't defined so ActionHero can't receive.
exports.productAdd = {
name: 'online/productAdd',
inputs: {
I don't know How Many Images are made? 1~10? or 1~100?
},
authenticate: true,
outputExample: {
'result':'success'
}
So I have two Questions:
How can actionhero receive the parameter without inputs defined?
Can I object with Image Data send to ActionHero by Ajax?
Thank You.
I change reduceParams function in actionProcessor.js.
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
i can define on inputs like below.
'img_*' : {required: false}
and Then I make middleware
var actionHeroMiddleware = {
name: '-',
global: true,
priority: 1000,
preProcessor: function(data, next) {
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
next();
},
stop: function(api, next) {
next();
}
};
api.actions.addMiddleware(actionHeroMiddleware);
next();
On the click event of a search button I'm sending the search text as parameter to a method on the controller. That method will return back a tool object that has properties like Name and Price in it. I can see the method is returning the tool object to the javascript and I can see the object is of tool type in the javascript but I cannot get the properties out of this object. How can I do something like this: document.getElementById('QSPrice').value = data.Price
VB.net
Function TestQuickSearch(ByVal searchItem As String) As Tool
Dim QSVM As Model.SearchViewModel = New Model.SearchViewModel()
Dim returnedItem = QSVM.GetToolByItemNum(searchItem)
Return returnedItem
End Function
JavaScript
$("#btnQuickSearch").live("click", function (e) {
var searchText = document.getElementById('txtQuickSearch').value
if(searchText.length !== 0) {
var Url = '#Url.Content("~/Route/QuickSearch")';
$.ajax({
url: Url,
async: 'false',
type: 'GET',
data: {searchItem: searchText},
success: function (data) {
alert(data.Price);
},
error: function (error) {
//Show Message
}
});
} else {
//Show Message
}
});
This is what I ended doing.
vb.net Code
Function QuickSearch(ByVal searchItem As String) As JsonResult
Dim QSVM As BusinessModel.QuickSearchViewModel = New BusinessModel.QuickSearchViewModel()
Dim returnedItem = QSVM.GetToolItemByItemNum(searchItem)
Return Json(New With {Key .results = returnedItem}, JsonRequestBehavior.AllowGet)
End Function
JavaScript Code
$("#btnQuickSearch").live("click", function (e) {
var searchText = document.getElementById('txtQuickSearch').value
if(searchText.length !== 0) {
var Url = '#Url.Content("~/Route/QuickSearch")';
$.ajax({
url: Url,
async: 'false',
type: 'GET',
dataType: 'json',
data: {searchItem: searchText},
success: function (results) {
for (var key in results) {
if(results[key] !== null){
var obj = results[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
switch(prop) {
case "Price":
document.getElementById('QSPrice').value = obj[prop];
break;
case "Description":
document.getElementById('QSDescription').value = obj[prop];
break;
case "Class":
document.getElementById('QSClass').value = obj[prop];
break;
case "QtyOnHand":
document.getElementById('QSQty').value = obj[prop];
break;
case "TakeOrderF":
var boolValue;
if(obj[prop] == true){
boolValue = "Yes";
}
else{
boolValue = "No";
}
document.getElementById('QSCanOrder').value = boolValue;
break;
case "Warranty":
document.getElementById('QSWarranty').value = obj[prop];
break;
}
}
}
}
else{
showMessage("Item Not Found.");
}
}
},
error: function (error) {
showMessage("Item Not Found/json error.");
}
});
} else {
//Show Message
showMessage("Item Not Found.");
}
});
I build a prototype that handle pages, I successfully add (push), but can get the data, I failed:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
Here the javascript page handler:
var Pages = new Array();
PageContainer = function () //constructor for the proxy
{
// this._baseURL = url;
};
PageContainer.prototype =
{
AddPage: function (data) {
if (data == null) return;
Pages.push({ PageID: data.PageID, SegmentID: data.SegmentID });
},
GetPage: function (PageID) {
alert('getPage('+PageID+')=' + JSON.stringify(Pages));
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
var dt = { PageID: Pages[foundImageIndex].PageID, SegmentID: Pages[foundImageIndex].SegmentID };
return dt;
}
};
I call from other js as following:
var gPageContainer = new PageContainer();
for (var i = 0; i < SegStruct.SegmentsCount; i++) {
var segRClass = //get from webservice
gPageContainer.AddPage({ PageID: i, SegmentID: segRClass.SegmentID });
}
I trying to call: gPageContainer.GetPage(1); but it failed in GetPage: function (PageID) it returns -1 in:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
foundImageIndex always -1
why?
Simply add the following before the constructor:
if (typeof Array.prototype.indexFirst == 'undefined') {
Array.prototype.indexFirst = function (validator) {
for (var i = 0; i <= this.length - 1; i++) {
if (validator(this[i])) {
return i;
}
}
return -1;
};
}