Selectize.js not rendering options from server - c#

Using Selectize.js, I am able to retrieve data from the server but nothing appears in the drop down on the callback. Maybe it is the format of the data?
On the server, I'm using System.Web.Script.Serialization.JavaScriptSerializer to serialize a datatable (C#) and return the JSON object.
At a loss as to why the data isn't rendering.
Code:
<div class="sandbox">
<label for="select-movie">Movie:</label>
<select id="select-movie" class="movies" placeholder="Find a PO..."></select>
</div>
<script class="show">
$('#select-movie').selectize({
valueField: 'ID',
labelField: 'PO',
searchField: 'PO',
create: false,
options: [],
render: {
option: function (item, escape) {
return '<div>' + item.PO + ' ' + escape(item.PO) '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
var dataString = JSON.stringify({
prefixText: query
});
$.ajax({
type: "POST",
url: "Default.aspx/GetUsers",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: dataString,
error: function () {
callback();
},
success: function (msg) {
alert(msg.d);
callback(msg.d);
}
});
}
});
</script>
Data returned from server:
{
"d":"[
{
\"ID\":1,
\"PO\":\"PO/REQ Number\"
},
{
\"ID\":262,
\"PO\":\"this po\"
},
{
\"ID\":264,
\"PO\":\"Test po\"
},
{
\"ID\":267,
\"PO\":\"Test PO 1\"
}
]"
}

The data returned from server (msg.d) is a String. It must be an Array.
You should check your Default.aspx/GetUsers method to return it.

Related

Typeahead.js call ASP.Net core API

I want to use typeahead.js to my autocomplete search bar. I have an API which return a list of subjects. Now I want to use that API for typeahead.
I have checked my API and it works. It seems I have problems with AJAX but I can not figure it out what's wrong?
$('#inputSearch').typeahead({
hint: true,
highlight: true,
minLength: 1,
source: function (request, response) {
$.ajax({
url: "http://localhost:59602/api/subject",
data: "{'prefix': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
items = [];
map = {};
$.each(data, function (i, item) {
var id = item.id;
var name = item.name;
map[name] = { id: id, name: name };
items.push(name);
});
response(items);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
})
}
});
My search bar
<div class="col">
<input asp-for="subjectID" class="form-control form-control-lg form-control-borderless" type="text" placeholder="Search subject"
id="inputSearch" data-provide="typeahead" autocomplete="off">
</div>
Just had a quick look at the docs and it looks like you need two objects inside .typeahead.
$('.typeahead').typeahead({ // <- typeahead settings.
minLength: 3,
highlight: true
}, // <- comma + new object below for data.
{
name: 'my-dataset',
source: mySource // <- put your source here.
});
hth.

Posting to WebMethod with ajax error

Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>

autocompletion in jquery not working

I am using json result to populate the textbox and I can see the values are returned to Razor view using alert. But I am unable to bind them to textbox.
in my layout.cshtml i am loading the jquery files.
![This is in the header section of my layout page][1]
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/jquery-ui")
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/Site")
This is my index file,
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
any help is greatly appreciated.
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
async : false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
try the async:false in ajax
You haven't posted your data response, but if it is an array of strings, the following should do it.
success: function (data) {
response(data);
},
Since you've already provided the data in the format that it needs (a label and a value), you don't have to map the data. Just pass it directly into the response.

Get response from c# code behind to javascript

I am making jquery ajax call to post data on server and return response from whether completed successfully or not. But I am not able to see response in js.
js:
$.ajax({
url: 'ajaxExecute.aspx/CAO2',
data: strRequest,
dataType: "json",
contentType: "application/json",
cache: false,
context: document.body,
type: 'POST',
success: function (response) {
alert(response);
window.parent.$('#divDialog').dialog('close');
window.parent.$('#divDialog').dialog('destroy');
window.parent.$('#divDialog').html(response);
window.parent.$('#divDialog').attr('title', 'Error');
window.parent.$('#divDialog').dialog({ show: "blind", modal: true, dialogClass: 'alert', zIndex: 99999, resizable: false, draggable: false });
}
});
here i am not getting any alert but able to see response in Chrome -> Inspect Element -> Network -> Response
cs
[WebMethod]
public static void CAO2(string Guardian, string CIFID, string EmploymentType)
{
try
{
if (Guardian != "" && CIFID != "" && EmploymentType != "" )
{
if (Generix.putCustomerDetailsPart2(Guardian,CIFID,EmploymentType)) // Will Create SQL Query And Execute on Database
{
HttpContext.Current.Response.Write("Information Submitted Successfuly..!!<br/><br/>Please Visit Your Nearest Branch...");
}
else
{
HttpContext.Current.Response.Write("Error Occurred While Processing Information..!!<br/><br/>Please Try Again...");
}
}
else
{
HttpContext.Current.Response.Write("Missing Information..!!");
}
}
catch (Exception xObj)
{
HttpContext.Current.Response.Write("ERROR: " + xObj.Message);
}
}
where I am missing?
Use the reponseType as "json" and try response.d. Also add error function to find where exactly the problem occurs
$.ajax({
url: 'ajaxExecute.aspx/CAO2',
data: strRequest,
dataType: "json",
contentType: "application/json",
responseType:"json",
cache: false,
context: document.body,
type: 'POST',
success: function (response) {
alert(response.d);
},
error: function(xhr) {
alert(xhr.responseText);
}
});

can not invoke webmethod to save handsonTable

I want to save handsontable data into json file,I have a javas cript method to get all data from handsontable as
$('button[name=save]').click(function () {
var str = handsontable.getData();
var value = JSON.stringify(str);
$.ajax({
url: "WebService.asmx/getData",
data: { 'data': value },
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function (res) {
if (res.result == 'ok') {
alert('Data saved');
}
else {
alert('Save error');
}
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
}
});
});
But I am not able to invoke WebService.asmx/getData(List data) .
public string getData(List<String> data)
{
return "";
}
What I need to pass in data:??...Please help.
data: { 'data': str },
dataType: 'json',
contentType: 'application/json',
With the contentType setting you are telling the server that you are sending JSON data, but you aren't. { 'data': str } is not a JSON string; it is a standard Javascript object literal. You are invoking the default jQuery behaviour for creating HTTP requests. This means you're sending a regular HTTP request, something like:
?data=thedata
To send actual JSON data, you need to call JSON.stringify:
data: JSON.stringify({ 'data': str }),
dataType: 'json',
contentType: 'application/json',
you must write before methode
[WebMethod]
and change parameters of method from List to string
then you can split it

Categories