Calling ASMX webservice from JQuery Autocomplete - javascript

I'm currently trying to get the response from an asmx service and use it in an autocomplete textbox
Here the code i'm currently using:
$(function () {
$("#<%=txtParentCat.ClientID %>").autocomplete({
selectFirst: true,
source: Magelia.WebStore.Admin.Scripts.Services.AutoCompleteServices.GetCategoriesFull,
extraParams: { contains: $('#<%=txtParentCat.ClientID %>').val(), storeId: '<%=this.Page.UnitOfWorkContext.StoreId.ToString() %>' },
minLength: 0,
delay: 0,
autoFocus: true,
dataType: 'json',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i], result: data[i] };
}
return rows;
},
formatItem: function (row) {
return row;
},
autofill: true,
highlight: false,
multiple: true,
multipleSeparator: ";"
,
response: function (event1, ui) {
var input = $('#<%=txtParentCat.ClientID %>');
input.on('keydown', function (event) {
var key = event.keyCode || event.charCode;
if (key == 8 || key == 46)
select = false;
else
select = true;
});
if (select == true && ui.content.length > 0) {
var $userVal = this.value;
var $newVal = ui.content[0].value;
if ($userVal != "") {
var n = $newVal.toLowerCase().indexOf($userVal.toLowerCase());
if (n == 0)
n = n + $userVal.length;
if (n != -1) {
$("#<%=txtParentCat.ClientID %>").val($newVal);
setSelectionRange($("#<%=txtParentCat.ClientID %>").get(0), n, $newVal.length);
}
}
}
}
});
});
I keep getting a 500 internal error which i think must be because i'm sending the parameters needed to call the webservice the wrong way.
Here the parameters required to call the service:
Magelia.WebStore.Admin.Scripts.Services.AutoCompleteServices.GetCategoriesFull(contains,storeId,onSuccess,onFailed,userContext)
Any help is much appreciated. Thank you in advance :)

Related

Bind function to Ajax Form Success Event

I need to call a function with a conversion tag when a form is successfully submitted via ajax.
Since the Javascript for handling the form is generated by the CMS of the site I am not able to change it. I don't want to rewrite the whole ajax call and just call my function when the form successfully submits
This is the Javascript Code generated by the CMS (it's just a snippet)
qpzP: function(e, t, n) {
"use strict";
Object.defineProperty(t, "__esModule", {
value: !0
});
var r = n("ZClI"),
i = (window.ElementFormContainer || window.ElementBase).extend({
$form: null,
ajax: !0,
time: null,
wakeup: function() {
return this.time = new Date, this.$form = this.getViewport().jQuery("> form", this.$element[0]), this.$form.on("submit", function(e) {
this.ajax && (e.preventDefault(), this.submit())
}.bind(this)), this
},
submit: function() {
if ("undefined" != typeof cms && cms) return !1;
if (!this.ajax) return this.$form.submit(), this;
var e = $('input[type="file"]:not([disabled])', this.$form);
e.each(function(e, t) {
t.files.length > 0 || $(t).prop("disabled", !0)
});
var t = new FormData(this.$form[0]);
"undefined" != typeof webcard && "culture" in webcard && webcard.culture && t.append("culture", webcard.culture), e.prop("disabled", !1), t.append("id", this.getId()), t.append("tac", Math.floor(((new Date).getTime() - this.time.getTime()) / 1e3));
var n = "" != this.$form.attr("action") ? this.$form.attr("action") : "/form_container/submit";
return $.ajax({
url: n,
data: t,
processData: !1,
contentType: !1,
type: "POST",
success: function(e) {
this.$element.find(".ed-element").each(function() {
this.element.destroy()
}), this.$element.html(e), $(e).is(".wv-success") ? this.getViewport().notify("form.success", [this, this.$form]) : this.getViewport().notify("form.error", [this, this.$form]), this.wakeup();
var t = this.$element.find(".ed-element"),
n = [];
t.each(function(e, t) {
var i = r.a.getTypeClassName($(t).attr("class"));
i in window && n.push(new window[i](t))
}.bind(this)), animations.initSubsequent(n)
}.bind(this)
}), this
},
setAjax: function(e) {
return this.ajax = e, this
}
});
t.default = i
},
This is what I though could work:
/* Conversion Tracking */
$(function () {
$('form').bind('submit', function () {
gtag('event', 'conversion', {'send_to': 'AW-xxx/xxx'});
console.log('gtracking_sent');
});
});
But it doesn't work.
Ideas on how to achieve this?

Tree_view undefined after read kendo tree

Here's my problem:
I load a first time my tree to display him.
I can change the value of the Session's files name "state" to enable or disable a node in my tree.
But after I change ne value in my database and return the JSON, I read again the tree to refresh my tree with the changes but it's failed and write in console :
" TypeError: Tree_view.getElementsByClassName(...)[0].children[(item.id_perso - 1)].children[1] is undefined".
That I don't understand is I pass my first time by these functions and it work well, but when I reload it failed apparently because the it undefined.
Thank's for any help.
$(document).ready(function() {
$('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node);
var treeview = $('#Tree_view').data('kendoTreeView');
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
if (item.level() == 0) {
setTimeout(function() { waitDisable(item, treeview); }, 1000);
}
}
function waitDisable(item, treeview) {
if (item.fields.type == "parcours")
{
var node = Tree_view.getElementsByClassName('k-group')[0].children[item.id_perso - 1].children[1].children;
for (i = 0; i < item.children._data.length; i ++)
{
if (item.children._data[i].state != null) {
node[i].children[0].children[1].className = "k-in k-state-disabled";
node[i].children[0].children[0].className = ".k-icon-remove";
}
else node[i].children[0].children[0].className = "k-icon k-plus";
addRow(node, item, i, treeview);
}
}
}
var cmp = 0;
var One_Time = false;
function addRow(node_Here, item, i, treeview) {
var actual_row = node_Here[i].children[0];
if (actual_row.childNodes.length < 3) {
var newSpan = document.createElement('button');
if (item.children._data[i]._childrenOptions.data.state != null) {
newSpan.appendChild(document.createTextNode("Re-Up"));
newSpan.className = "change_state btn btn-success btn-xs";
}
else {
newSpan.appendChild(document.createTextNode("Down"));
newSpan.className = "change_state btn btn-danger btn-xs";
}
actual_row.appendChild(newSpan);
}
cmp += 1;
if (cmp == item.children._data.length)
One_Time = true;
if (One_Time) {
addClickListner(item, i, treeview);
One_Time = false;
cmp = 0;
}
}
function addClickListner(item, i, treeview) {
$(".change_state").click(function (event) {
var name_Promo_Rm = event.target.parentNode.children[1].textContent;
var User_Select = event.view.Parcours.transport.read.data.user_id;
$.ajax({
url: '#Url.Action("ChangeStatutBase", "Users")',
type: 'GET',
dataType: 'json',
data: { Name_Promo: name_Promo_Rm, User_id: User_Select },
});
refreshTree(treeview);
})
}
// Refresh tree
function refreshTree(treeview) {
// Save open items
saveExpandedItems(treeview);
// Reload data source
treeview.dataSource.read();
// Load open items
console.log("OKKKKKKK");
setTimeout(loadExpandedItems(), 600);
}
I've resolved my problem, in the "setTimeout" in the bottom I've placed "()" in the first parameter and it doesn't put the pause and data don't have the time to be loaded.

how can i reset #html.Listbox to empty using jquery in Asp.net MVC

#Html.ListBox("project type", new SelectList(db.tblTypes.ToList(), "ID", "Name"),
new { multiple = "multiple", id = "projectType" })
here is my ajax code where i want it to empty
$("#frm").submit(function (e) {
e.preventDefault(e);
//$('#frm').submit();
var e = document.getElementById("myselect");
var selectedIndices = [];
$(function () {
$.each($('select[multiple]'), function (sIndex, sValue) {
if (sIndex == 0) {
$.each(this.options, function (oIndex, oValue) {
if (this.selected)
selectedIndices.push(oIndex);
});
} else {
for (var i = 2; i < selectedIndices.length; i++) {
this.options[selectedIndices[i]].selected = true;
}
}
});
});
var project = {
ProjectTitle: $('#ProjectTitle').val(),
ProjectNumber: $('#ProjectNumber').val(),
Portfolio: $('#Portfolio').val(),
TotalSalesCC: $('#TotalSalesCC').val(),
grossMarginCC: $('#GrossMarginCC').val(),
projectMarginCC: $('#ProjectMarginCC').val(),
projectStatus: e.options[e.selectedIndex].value,
ImpStartDate: $('#ImpStartDate').val(),
ImpEndDate: $('#ImpEndDate').val(),
projectType: selectedIndices,
isSurvey:$('#hide').val()
};
if ($("#ProjectNumber").val() == "") {
$.growl.error({ message: 'Please fill project number.' });
return false;
}
if ($("#ProjectTitle").val() == "") {
$.growl.error({ message: 'Please fill project title.' });
return false;
}
if (selectedIndices.length == 0 || selectedIndices.length < 1) {
$.growl.error({ message: 'Please choose atleast one project type.' });
return false;
}
var s=$("#ImpStartDate").val();
var e = $("#ImpEndDate").val();
if (s == "" )
{
$.growl.error({ message: 'Please enter start date.' });
return false;
}
else if (e == "")
{
$.growl.error({ message: 'Please enter end date.' });
return false;
}
else if (s > e) {
$.growl.error({ message: 'End date should be greater than start date.' });
return false;
}
var date = new Date();
date.setDate(date.getDate()-1);
//$('#ImpStartDate').datepicker({
// startDate: date
//});
$.ajax({
type: "POST",
url: "/Projects/Create",
data: JSON.stringify(project),
contentType: "application/json; charset=utf-8",
success: function (s) {
console.log(s);
LoadProjectsGrid();
//LoadprojectsGrid();
// End For
$.growl.notice({ message: ' Your Project created successfuly' });
$("#projectType").html('');
},
failure: function (response) {
alert(response.d);
}
});
// clear list via dom
// or clear list via jquery & dom
$('#frm').find(".has-success").removeClass("has-success");
$('#frm').find(".glyphicon-ok").removeClass("glyphicon-ok");
$('.panel-collapse').collapse('hide');
$('.panel-title').attr('data-toggle', 'collapse');
document.getElementById('frm').reset();
$('#accordion .ui-accordion-content ').hide();
});
If you want to empty it on the Client side use
$("#projectType").html('');
And If you want an empty Value on the server side use
$("#projectType").val('');

Can ghost.py scrape a web page with javascript setInterval update repeatedly?

I plan to use Ghost.py to scrape a web page which is updated every 5 seconds by setInterval.
How can I scrape the updated data by Ghost.py repeatedly, once there is a new update by this script?
The setInterval code below:
(function () {
var template;
(function () {
template = $("#template1 tbody").html();
GetData();
})();
function GetData() {
var max = 100,
sn = $.data(document, "sn");
if (sn === undefined) {
sn = 0;
} else {
sn = parseInt(sn, 10);
}
$.ajax({
url: path + "ashx/notice.ashx",
async: true,
cache: false,
data: {
act: "GetBotSignal",
sn: sn,
max: max
},
type: "get",
dataType: "json",
success: function (data) {
if (data !== null && data.length !== 0) {
var html = "";
var expselbox = $(".exp-sel-box");
for (var i = 0, j = data.length; i < j; i++) {
var item = template;
item = item.replace(/\{0}/g, data[i].SignalOccurTime);
(parseFloat(data[i].Ratio) >= 2 && parseFloat(data[i].Probability) >= 50) ? " sp" : "");
html += item;
}
expselbox.prepend("<tr ef=\"1\" style=\"height:0px;\"></tr>");
expselbox.find("tr[ef=1]").animate({ "height": (34 * data.length) + "px" }, "fast", function () {
expselbox.find("tr[ef='1']").remove();
expselbox.prepend(html);
expselbox.find("tr:hidden").fadeIn("fast");
expselbox.find("tr:gt(" + max + ")").remove();
$.data(document, "sn", data[0].SN);
ScrollBar($(".expscall-out"), 642, 342, true);
});
}
}
});
}
if (srvTime.getHours() > 7 && srvTime.getHours() < 14) {
setInterval(function () {
GetData();
}, 5000);
}
})();

FB.api("/me/apprequests/?request_ids="+ids) returning empty data

Im using javascript SDK to send some invitations to friends, and i neeed to get the friends IDs. this is part of my code:
function RequestFriendship() {
FB.getLoginStatus(function (response) {
if (response.session && response.perms != null && response.perms.indexOf('user_about_me') != -1) {
Request();
}
else {
FB.ui({
method: 'auth.login',
perms: 'user_about_me,publish_stream',
display: 'iframe'
}, function (response3) {
if (response3 != null && response3.perms != null && response3.perms.indexOf('user_about_me') != -1) {
Request();
}
else {
alert('No invitations sent.');
}
});
}
});
and my Request method is:
function Request() {
FB.ui({ method: 'apprequests', message: 'Mensaje Publicidad', data: '', title: 'Titulo publicidad' },
function (response) {
if (response && response.request_ids) {
var ids = response.request_ids;
FB.api("/me/apprequests/?request_ids=" + ids[0], function (response2) {
alert(JSON.stringify(response2, replacer));
});
}
});
}
But every time run it i get an empty data in the FB.api("/me/apprequests/?request_ids=" + ids[0]. I dont know what im doing wrong, i think i worked fine for me some time ago but now it isnt. Is this a permission problem? I think user_about_me is enough to ask for apprequest but not sure anymore. Any help? Thanx
WEll i found the answer myself. Just use this:
if (response && response.request_ids) {
var ids = response.request_ids;
var _batch = [];
for (var i = 0; i < ids.length; i++) {
_batch.push({ "method": "get", "relative_url": ids[i] });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// var obj = eval('(' + res + ')');
for (var j = 0; j < res.length; j++) {
body = res[j].body;
var myObject = eval('(' + body + ')');
friendID = myObject.to.id;
// here you have every friendID
}
});
}
}
:)
You don't actually need to create a batch request. You can use the ids parameter on the root and give it the request_ids value returned from the dialog directly:
FB.api("/?ids=" + response.request_ids, callback);

Categories