I am creating a notification center, naturally it must be visible throughout the site; So the question is how do I do it.
Create a name.js file inside the static folder but it seems that something is missing since apart from the delay in the app itself it is not visible outside it.
view.py
#csrf_exempt
def NewsSubjects(request):
if request.is_ajax() == True:
queryset = Downloads.objects.all().order_by('register_date').values()[:5]
data=list(queryset)
return JsonResponse(data, safe=False)
urls.py
path('alerts/', views.NewsSubjects, name='alerts'),
/static/js/notifications.js
$.ajax({
// initialize an AJAX request
url: "alerts",
// al estar en static no se usa el name del URL ('control:alert') sino el PATH (alerts/)
type: "GET",
datatype:'json',
success: function(data) {
console.log('cambio')
var opciones = document.getElementById("nuevasDisciplinas");
var countAlert = document.getElementById("countAlert");
var listaDisciplinas = ''
for (var i = 0; i < data.length; i++) {
// console.log(data[i]);
var nombDis = data[i].category_name
var fechaCreacion = data[i].register_date
// var d = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(fechaCreacion)
// var m = new Intl.DateTimeFormat('en', { month: 'short' }).format(fechaCreacion)
// var a = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(fechaCreacion)
var icon = '<divclass="mr-3"><divclass="icon-circle bg-primary"><iclass="fas fa-file-alt text-white"></i></div></div>'
var body ='<div><divclass="small text-gray-500">'+fechaCreacion+'</div><spanclass="font-weight-bold">'+nombDis+'</span></div>'
listaDisciplinas += icon+body
}
opciones.innerHTML = listaDisciplinas;
countAlert.innerHTML = data.length;
},
error: function() {
console.log("The information could not be obtained");
}
});
master.html
<script src="{% static 'js/notifications.js' %}"></script>
the idea is simple, bring the latest records according to the date of registration (the best option would be the login date to the system but good), this works in the notification app but not in the rest.
It returns the message that I put in case of error.
PS: if you can lend me a hand with the formatting of the date it would be fine too
you have to use the path of the url instead of the name, that is, the name of the app/url/
Django the urls.py they consist of path(this_url, view, name_url) so to use it throughout the Django site you must use app/this_url/
in my case
my urls.py
path('alerts/', views.NewsSubjects, name='alerts'),
in the ajax url it would be
$.ajax({
url: "app_name/alerts/",
...
});
Related
How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.
def index(request):
if Movie.objects.order_by('-stars').exists():
movie = list(Movie.objects.order_by('-stars'))
if TV.objects.order_by('-stars').exists():
tv = TV.objects.order_by('-stars')
print(tv)
context = {
'movie':movie,
}
return render(request, 'Movie/index.html',context)
fetchTrendingResults("all", "week")
var mediaType = document.getElementById("media_type")
mediaType.addEventListener("change", function(event) {
fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day")
})
function fetchTrendingResults(media_type, time_window) {
var trendingDiv = document.getElementById("trendings")
trendingDiv.innerHTML = ""
if (media_type == "score"){
var js_list = {{movie}};
}
else{
fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}}
// todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。
)
.then(res => res.json())
.then(data => {
for (let i=0; i<data.results.length; i++) {
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "card");
mainDiv.setAttribute("style", "width: 18rem;");
var img = document.createElement("img");
img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path);
img.setAttribute("class", "card-img-top");
img.setAttribute("alt", "...");
var body = document.createElement("div");
body.setAttribute("class", "card-body");
var title = document.createElement("h5");
title.setAttribute("class", "card-title");
if (data.results[i].name) {
title.innerHTML = data.results[i].name;
} else {
title.innerHTML = data.results[i].title;
}
//var text = document.createElement("p");
//text.setAttribute("class", "card-text");
//text.innerHTML = data.results[i].overview;
var link = document.createElement("a");
link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/");
link.setAttribute("class", "btn btn-primary");
link.innerHTML = "View Details";
body.appendChild(title);
//body.appendChild(text);
body.appendChild(link);
mainDiv.appendChild(img);
mainDiv.appendChild(body);
document.getElementById("trendings").appendChild(mainDiv);
}
})
}
}
How do I pass a django model to javascript?
Specifically, I want to pass a django Movie model to javascript.
In javascript, I would like to display the id something in the movie model at the time of score with an if statement.
You can send model data by just returning JsonResponse from the view (and for example creating JSON dict by forlooping QuerySet, or using model_to_dict Django built-in method) or by preserving your logic and sending html you need to override - even better - you can do both ways at the same time.
So, basically you write view like this:
from django.forms import model_to_dict
from django.http import Http404
def custom_ajax_view(request):
if request.method != 'POST':
raise Http404
movies = Movie.objects.order_by('-stars')
movie_dict = {}
if movies.exists():
movie_dict = {obj.id: model_to_dict(obj) for obj in movies}
tv = TV.objects.order_by('-stars')
tv_dict = {}
if tv.exists():
tv_dict = {obj.id: model_to_dict(obj) for obj in tv}
context = {
'movie': movie,
}
html = render_to_string(
'Movie/index.html', context=context)
return JsonResponse({
'movies': movie_dict,
'tvs': tv_dict,
'html': html,
})
And then you retrieve data via Ajax method (I prefer using jQuery for that) by writing:
$.ajax({
url: CUSTOM_AJAX_URL,
type: 'post',
dataType: 'json',
success: function (data) {
// Here you retrieve your data and you can do something with it.
console.log(data)
}
});
You also can resolve your CUSTOM_AJAX_URL using template logic (post it at the end of template)
<script>
const CUSTOM_AJAX_URL = "{% url 'custom_ajax_view' %}";
</script>
<script src="{% static 'your_script_name.js' %}"></script>
Then your script should see the CUSTOM_AJAX_URL (if you use script not directly by using inline method, but including script via script tag and placing it with static method in the code). If you place it directly, you can pass URL directly to the AJAX method.
I'm trying to make an ajax call (I specifically don't want to do it using ActionLink).
I'm having a controller that is like this:
public IActionResult ExportUsers(List<string> listOfEmails)
{
/*some data processing*/
return File(result, "text/csv", "ExportCandidates.csv");
}
On the other side with ajax I do this simple call:
$.ajax({
url: '/Admin/Testcenter/GenerateInvitationPreview',
type: 'post',
data: {
//some input data to send to the controller
},
success: function (response) {
)
}
});
I know there exists something for pdf files where you return a base64 file and with the response in the ajax call you just write something like pdfWindow.document.write(...) and this will open a new window with a pdf file.
Is there a way to extract the response for my CSV file and generate it so the user downloads it ?
USE NPOI Library for Excel Sheet Generation
//Generate Excel Sheet
try
{
Guid gid = Guid.NewGuid();
string ext = ".xls";
string[] Headers = { "Appointments Id", "Date of Appointment", "Doctor Name", "Patient Name", "Visit Type", "Status" };
string fileName = "AppointmentsExcelSheet_" + gid.ToString() + ext;
var serverpath = _env.ContentRootPath;
string rootpath = serverpath + "/wwwroot/ExcelSheets/" + fileName;
FileInfo file = new FileInfo(Path.Combine(rootpath, fileName));
var memorystream = new MemoryStream();
using (var fs = new FileStream(rootpath, FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Appointments List");
IRow row = excelSheet.CreateRow(0);
var font = workbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)FontBoldWeight.Bold;
for (var i = 0; i < Headers.Length; i++)
{
var cell = row.CreateCell(i);
cell.SetCellValue(Headers[i]);
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
}
var result = _Appointment.GetAppoinmentsPDf();
int index = 1;
foreach (var app in result.Items)
{
//var PatientDob = Convert.ToDouble(app.PatientDOB);
row = excelSheet.CreateRow(index);
row.CreateCell(0).SetCellValue(app.AppointmentId);
row.CreateCell(1).SetCellValue(app.DateofAppointment+" "+app.TimeofAppointment);
row.CreateCell(2).SetCellValue(app.DoctorFullName);
row.CreateCell(3).SetCellValue(app.SelectedPatientName);
row.CreateCell(4).SetCellValue(app.PurposeofVisit);
if (app.IsActive == false)
{
row.CreateCell(5).SetCellValue("Inactive");
}
else
{
row.CreateCell(5).SetCellValue("Active");
}
index++;
}
workbook.Write(fs);
}
using (var filestream = new FileStream(rootpath, FileMode.Open))
{
filestream.CopyToAsync(memorystream);
}
memorystream.Position = 0;
//send filepath to JQuery function
response.Msg = "/ExcelSheets/" + fileName;
}
catch (Exception Ex)
{
//exception code
}
return Ok(reponse.Msg)
//JavaScript
function AppointmentsExcelSheet() {
//var token = Token;
//var link = path;
debugger
$.ajax({
//'Content-Type': 'application/pdf.',
type: "GET",
url: "/api/Appointments/GetAppointmentsExcelSheet",
beforeSend: function () {
$.blockUI({
message: ('<img src="/images/FadingLines.gif"/>'),
css: {
backgroundColor: 'none',
border: '0',
'z-index': 'auto'
}
});
},
complete: function () {
$.unblockUI();
},
success: function (data) {
debugger
//downloads your Excel sheet
window.location.href = data.msg;
}
});
}
The best way to do what you want to do is to not use AJAX, but use either a link click that opens a new window (since you are passing in parameters) If you could use a
<form target="_blank">
to open a form response. Inside the form can be a field or fields that contains the list of emails (it can be one field, or multiple input fields with the same name). Your action handler can accept that list, parse it, and return a File response, and the natural result of opening the new window from the form post operation is a file that opens up.
I have integrated authorize.net accept.js embedded iFrame in my application. Having trouble setting the transaction respone in my lambda function to get the response. I've seen similar questions on stack overflow but nothing worked out for me yet.
Using Nodejs for my backend and angular7 for the front-end.
I successfully get the token from my lambda function so my iframe appears on the ui. I've set \"showReceipt\": false providing url for cancel & continue, since the documentation says I have to set the show receipt parameter "false" in order to communicate with the IFrameCommunicator.html in the ui. But when I click on "Pay" its stuck at "Processing.." for a long time.
Following are the request & response headers respectively from the network tab:
* Cookie: __cfruid=deb63d2f12d9690aeea838cf7f31ada6da92bc1c-1602260930
* Host: test.authorize.net
* Origin: https://test.authorize.net
* Referer: https://test.authorize.net/payment/payment
* Sec-Fetch-Dest: empty
* Sec-Fetch-Mode: cors
*
Sec-Fetch-Site: same-origin
{"resultCode":"Ok","messageCode":"Ok","transactionData":{"accountType":"Discover","accountNumber":"XXXX0012","transId":"40055282319","responseCode":"4","authorization":"TYIUU7","merchantName":"iMart Inc.","totalAmount":"1999.9","dateTime":"10/09/2020 4:20:27 PM"}}
I'm sure the transaction is happening looking at the response but not sure why it's not connecting with the communicator.
I've read the steps in the documentation and also followed the GitHub sample code-https://github.com/AuthorizeNet/accept-sample-app, which made me more confused since they both say different things at some places. Following are the steps I've accomplished until now :
Created a lambda hosted payment function with all the settings (followed the correct sequence) to get back a token.
Created a hosted payment form to display the iframe.
Able to make a payment --> get the receipt page --> routing to success screen.
What I'm trying to accomplish:
After I make the payment, initial idea was to trigger a different lambda function based on the response from authorize.net without communicating with IFrameCommunicator.html, but as I cannot do that, I want to get a response to initiate the next process at the backend.
Also, we're not storing any user details in our server and not interested in creating a customer profile unless it's a necessary step to get the transaction response. Please suggest the step integration if I can do it in the same lambda function I've created to get a token or I would have to create a different one for this and when will that step be implemented?
I know about the Webhooks but not sure if it's an absolute necessity at this point of time when I'm just trying to implement a simple transaction.
I'm a newbie and I couldn't find a lot of examples related to the same to resolve my issues/confusions. Would highly appreciate if I get a clear explanation on the steps here and where am I going wrong.
Following is the code -
accept-hosted.js Lambda function:
merchantAuthenticationType.setName('*****');
merchantAuthenticationType.setTransactionKey('******');
var transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
transactionRequestType.setAmount(Total);
var setting1 = new ApiContracts.SettingType();
var setting2 = new ApiContracts.SettingType();
var setting4 = new ApiContracts.SettingType();
var setting5 = new ApiContracts.SettingType();
var setting6 = new ApiContracts.SettingType();
var setting7 = new ApiContracts.SettingType();
var setting8 = new ApiContracts.SettingType();
var setting9 = new ApiContracts.SettingType();
var setting10 = new ApiContracts.SettingType();
var setting11 = new ApiContracts.SettingType();
setting2.setSettingName("hostedPaymentButtonOptions");
setting2.setSettingValue("{\"text\": \"Pay\"}");
setting1.setSettingName("hostedPaymentReturnOptions");
setting1.setSettingValue(
"{\"showReceipt\": false, \"url\": \"https://iMart.com/success.html\", \"urlText\": \"Continue\", \"cancelUrl\": \"https://iMart.com/error.html\", \"cancelUrlText\": \"Cancel\"}");
setting10.setSettingName("hostedPaymentOrderOptions");
setting10.setSettingValue("{\"show\": false, \"merchantName\": \"iMart Inc.\"}");
setting5.setSettingName("hostedPaymentPaymentOptions");
setting5.setSettingValue("{\"cardCodeRequired\": true, \"showCreditCard\": true, \"showBankAccount\": false}");
setting7.setSettingName("hostedPaymentShippingAddressOptions");
setting7.setSettingValue("{\"show\": false, \"required\": false}");
setting8.setSettingName("hostedPaymentBillingAddressOptions");
setting8.setSettingValue("{\"show\": false, \"required\": false}");
setting6.setSettingName("hostedPaymentSecurityOptions");
setting6.setSettingValue("{\"captcha\": true}");
setting4.setSettingName("hostedPaymentStyleOptions");
setting4.setSettingValue("{\"bgColor\": \"blue\"}");
setting9.setSettingName("hostedPaymentCustomerOptions");
setting9.setSettingValue("{\"showEmail\": false, \"requiredEmail\": false, \"addPaymentProfile\": true }");
setting11.setSettingName("hostedPaymentIFrameCommunicatorUrl");
setting11.setSettingValue("{\"url\": \"https://iMart.com/IFrameCommunicator.html\"}");
var settingList = [];
settingList.push(setting2);
settingList.push(setting10);
settingList.push(setting5);
settingList.push(setting7);
settingList.push(setting8);
settingList.push(setting6);
settingList.push(setting4);
settingList.push(setting9);
settingList.push(setting11);
settingList.push(setting1);
var alist = new ApiContracts.ArrayOfSetting();
alist.setSetting(settingList);
var firstname = new ApiContracts.UserField();
firstname.setName('First Name');
firstname.setValue(firstName);
var lastname = new ApiContracts.UserField();
lastname.setName('Last Name');
lastname.setValue(lastName);
var userFieldList = [];
userFieldList.push(firstname);
userFieldList.push(lastname);
var userFields = new ApiContracts.TransactionRequestType.UserFields();
userFields.setUserField(userFieldList);
var transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
var transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
var transactionSetting3 = new ApiContracts.SettingType();
transactionSetting3.setSettingName('emailCustomer');
transactionSetting3.setSettingValue('true');
var transactionSetting4 = new ApiContracts.SettingType();
transactionSetting4.setSettingName('headerEmailReceipt');
transactionSetting3.setSettingValue('You are all set!');
var transactionSetting5 = new ApiContracts.SettingType();
transactionSetting5.setSettingName('footerEmailReceipt');
transactionSetting5.setSettingValue('This is the footer');
var getRequest = new ApiContracts.GetHostedPaymentPageRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setTransactionRequest(transactionRequestType);
getRequest.setHostedPaymentSettings(alist);
var ctrl = new ApiControllers.GetHostedPaymentPageController(getRequest.getJSON());
const basicAuth = encode.encode("*****", 'base64');
await axios({
method: 'post',
url: 'https://apitest.authorize.net/xml/v1/request.api',
headers: {
'Authorization': 'Basic '+basicAuth,
'Content-Type': 'application/json'
},
data:JSON.stringify(ctrl._request)
}).then(async (data : any)=>{
if(data.data.token) {
callback(null, data.data) ;
} else callErr(data);
});
async function callErr(data: any){
callback(null, res) ;
}
}
IFrameCommunicator.html:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Iframe Communicator</title>
<script type="text/javascript">
//<![CDATA[
function callParentFunction(str) {
if (str && str.length > 0
&& window.parent
&& window.parent.parent
&& window.parent.parent.AuthorizeNetPopup
&& window.parent.parent.AuthorizeNetPopup.onReceiveCommunication)
{
// Errors indicate a mismatch in domain between the page containing the iframe and this page.
window.parent.parent.AuthorizeNetPopup.onReceiveCommunication(str);
}
}
function receiveMessage(event) {
if (event && event.data) {
callParentFunction(event.data);
}
}
if (window.addEventListener) {
console.log('addEventListener');
console.log(receiveMessage);
window.addEventListener("message", receiveMessage, false);
} else if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage);
}
if (window.location.hash && window.location.hash.length > 1) { callParentFunction(window.location.hash.substring(1));
}
//]]/>
</script>
</head>
<body>
</body>
</html>
Angular code for showing the iFrame:
<iframe id="add_payment" class="embed-responsive-item panel" name="add_payment" width="100%" frameborder="0" scrolling="yes">
</iframe>
</div>
<form id="send_token" action="" method="post" target="add_payment" >
<input id="token" type="hidden" name="token" />
</form>
I have been struggling a lot since many days now with a time crunch. Would be really helpful if someone provides me with a good insight here. Please let me know if additional info is required. Thank you in advance!!!
Here are the answer for all your question, I hope it works :
1)if you are using iFrame then iFrameCommunicator is mandatory
2)the success url can only be used when you set "showReceipt" as true, here you cannot navigate automatically to yoour success page, this is the link for "Continue" button which appears when "showReceipt" is allowed
3)If you want to trigger any function or want to navigate after the response then add the following code in your html file
<script type="text/javascript">
$(document).ready(function () {
window.CommunicationHandler = {};
function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
window.CommunicationHandler.onReceiveCommunication = function (argument) {
console.log('communication handler enter', argument);
var params = parseQueryString(argument.qstr)
switch (params['action']) {
case "resizeWindow":
console.log('resize'); break;
case "successfulSave":
console.log('save'); break;
case "cancel":
console.log('cancel'); break;
case "transactResponse":
sessionStorage.removeItem("HPTokenTime");
console.log('transaction complete');
var transResponse = JSON.parse(params['response']);
console.log('transaction complete1', transResponse);
// window.location.href = '/checkout/complete';
}
}
//send the token
$('#send_hptoken').submit();
});
</script>
I have problems to get data from Weather Underground from a historical day (same script works fine for my current observations). Example for yesterday:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
heute=new Date();
jahr=heute.getFullYear();
monat=heute.getMonth()+1;
tag = heute.getDate()-1;
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/ea1cb0c0f1995212/history_'+jahr+monat+tag+'/q/pws:INORDRHE156.json",
dataType : "jsonp",
success : function(parsed_json) {
var minhumidity = parsed_json.history.dailysummary[0].minhumidity;
var day = parsed_json.history.dailysummary[0].date.pretty;
document.getElementById("z8").innerHTML = minhumidity;
document.getElementById("z9").innerHTML = date;
}
});
});
</script>
So "day" works for me, output is: November 13, 2017
But "minhumidity" should bei '90' (or some other value), but there will be just a blank.
I get both values (day and minhumidity) at the same way, where is the Problem?
Sorry for my english.
your url "http://api.wunderground.com/api/ea1cb0c0f1995212/history_'+jahr+monat+tag+'/q/pws:INORDRHE156.json" change it to (note that i changed ' with "):
<script>
heute=new Date();
jahr=heute.getFullYear();
monat=heute.getMonth()+1;
tag = heute.getDate()-1;
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/ea1cb0c0f1995212/history_"+jahr+monat+tag+"/q/pws:INORDRHE156.json",
dataType : "jsonp",
success : function(parsed_json) {
var minhumidity = parsed_json.history.dailysummary[0].minhumidity;
var day = parsed_json.history.dailysummary[0].date.pretty;
document.getElementById("z8").innerHTML = minhumidity;
document.getElementById("z9").innerHTML = date;
}
});
});
</script>
And please add var, let, const whatever to your variables. For example:
var heute = new Date();
var jahr = heute.getFullYear();
var monat = heute.getMonth()+1;
var tag = heute.getDate()-1;
My requirement is I have 2 controls Code and description, when I select the code description will automatically displays and I want to select multiple codes automatically display multiple descriptions in description control and vice versa.
For this scenario I am supposed to use "auto complete box" using page methods, for the first time I am using Telerik controls.
Now I am able to get Codes in code auto complete box and able to select multiple codes.
Now my question is how to select the description after selecting multiple codes using Java script/jQuery?
My code is like below
<telerik:RadAutoCompleteBox ID="RdAutoClassCode" runat="server" Width="150" DropDownHeight="150"
DropDownWidth="150" TokensSettings-AllowTokenEditing="True" OnClientTextChanged="OnClientChange" on>
<WebServiceSettings Method="GetISOCodesRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
function OnClientChange() {
debugger;
alert("Hi");
}
Text changed event is not firing using above code.
Please provide any sample for this?
Thanks in advance,
Srividya
I finally got the solution.
<telerik:RadAutoCompleteBox ID="RdAutoClassCode" runat="server" Width="150" DropDownHeight="70"
OnClientEntryRemoved="RemoveEntry" OnClientEntryAdded="addNewEntry" height="150" DropDownWidth="150"
TokensSettings-AllowTokenEditing="True">
<WebServiceSettings Method="GetISOCodesRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
<telerik:RadAutoCompleteBox ID="RdAutoClassDesc" runat="server" Width="150" DropDownHeight="70"
height="150" DropDownWidth="150" TokensSettings-AllowTokenEditing="True">
<WebServiceSettings Method="GetISOCodeDescriptionsRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
Web Methods:
[WebMethod]
public static AutoCompleteBoxData GetISOCodesRadCombobox(object context)
{
string searchString = ((Dictionary<string, object>)context)["Text"].ToString();
DataTable data = GetData(searchString, 0);
List<AutoCompleteBoxItemData> result = new List<AutoCompleteBoxItemData>();
foreach (DataRow row in data.Rows)
{
AutoCompleteBoxItemData childNode = new AutoCompleteBoxItemData();
childNode.Text = row["CodeNumber"].ToString();
childNode.Value = row["CodeNumber"].ToString();
result.Add(childNode);
}
AutoCompleteBoxData res = new AutoCompleteBoxData();
res.Items = result.ToArray();
return res;
}
[WebMethod]
public static AutoCompleteBoxData GetISOCodeDescriptionsRadCombobox(object context)
{
string searchString = ((Dictionary<string, object>)context)["Text"].ToString();
DataTable data = GetData(searchString, 1);
List<AutoCompleteBoxItemData> result = new List<AutoCompleteBoxItemData>();
foreach (DataRow row in data.Rows)
{
AutoCompleteBoxItemData childNode = new AutoCompleteBoxItemData();
childNode.Text = row["CodeDesc"].ToString();
childNode.Value = row["CodeDesc"].ToString();
result.Add(childNode);
}
AutoCompleteBoxData res = new AutoCompleteBoxData();
res.Items = result.ToArray();
return res;
}
private static DataTable GetData(string text, int Value)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["QMSDBCON"]);
DataSet ds = SqlHelper.ExecuteDataset(con, "usp_GetIsoCode", text, Value);
DataTable data = new DataTable();
// adapter.Fill(data);
data = ds.Tables[0];
return data;
}
JavaScript Calling for new entry:
function addNewEntry() {
debugger;
var autoCompleteBoxCode = $find("<%= RdAutoClassCode.ClientID %>");
var autoCompleteBoxDescription = $find("<%= RdAutoClassDesc.ClientID %>");
var entriesCount = autoCompleteBoxCode.get_entries().get_count();
var entry = new Telerik.Web.UI.AutoCompleteBoxEntry();
autoCompleteBoxDescription.get_entries().clear();
for (var i = 0; i < entriesCount; i++) {
var code = autoCompleteBoxCode.get_entries().getEntry(i).get_text();
_ClassCodeSelectedIndexChanged(code);
}
}
Calling server method using Json
function _ClassCodeSelectedIndexChanged(code) {
debugger;
var URL = window.location.protocol + "//" + window.location.host;
URL = URL + "/GetClassCodeAndDescription.aspx/GetISOCodesRadComboboxData";
$(document).ready(function () {
$.ajax({
type: "POST",
url: URL,
data: "{Code : '" + code + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
onsuccess(msg);
},
error: function (xhr) {
onerror(xhr);
}
});
});
}
jQuery("#textbox").blur(function() {
ajaxFunction(jQuery("#textbox").val());
});
function ajaxFunction(code){
// Your ajax call
}
Try this hopeFully this help.