Hi fellow programmers,
I have a database with some data. I Created a WCF Service that uses jQuery Autocomplete to get all names from the database. I get response with JSON but I want to display this in the autocomplete.
This is what my jQuery looks like:
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "/service.svc/GetData",
dataType: "jsonp",
data: {
DataName: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
I am fairly new to WCF and want to know what the next step is? How do I map the data so I can display it?
The JSON data output looks like this:
{"GetDataResult":[{"Name":"Fran $","CategoryId":102,"dataId":1,"IndexId":16,"InsertedDate":null,"Manual":false}
The autocomplete widget expects the array you supply to the response callback function to be in one of the following formats:
An array of strings, e.g. ["Hello", "Goodbye"]
An array of objects. Each object must have at least either a label property or a value property. It may have other properties as well.
So in your situation you can either:
Edit the server-side code that returns the JSON to conform to the format that the widget expects, or
Modify the results before passing them on to the response callback.
I'll focus on #2. The canonical way to do this is to use $.map to transform the array you got back from the server into the correct format, and then supply the resulting array to the response callback.
In your case that could look something like this:
success: function (data) {
response($.map(data.GetDataResult, function (item) {
return {
label: item.Name,
value: item.dataId
};
}));
}
Example: http://jsfiddle.net/yntrp063/
Note that the value property's value will be used inside of the textbox after you select an item--that might not be what you want.
Related
I want a dropdown menu that allows user to type in text..something like autocomplete with dropdown.
I have been trying this for a long time now and while going through other posts I found people suggesting Ajax but I could not use it.
What are the other options available ?
also,I have to bind the dropdown to a database query so the option must allow that.Thanks a ton!
you can try one of these two :
Chosen
Select2
Try using this code:
$("#DropDOwnID").select2({
ajax: {
url: "https://graph.facebook.com/v2.2/search", //method which returns the data for select2 OR in web forms use web service
type: 'GET',
multiple: true, //if dropdown can have multiple or not
dataType: 'json',
delay: 250,
data: function (params) {
return {
parametername: params.term, // search
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
var myResults = [];
$.each(data.data, function (index, item) {
myResults.push({
'id': item.key,
'text': item.name
});
});
return {
results: myResults
};
},
cache: true
},
minimumInputLength: 1,
});
You can try Select2 https://select2.github.io/
It has Ajax \ plain HTML mode, as well as ability to create pagination for large quantity of items.
You can create it using plain select as data source or even hidden input for ajax \ pagination
I am calling a method using JQuery ajax given below
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
alert(data);
alert(data["Countries"]);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});
C# code
public static string GetCountry()
{
var result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Countries.GetAll());
return result;
}
Now when I debug my code on server side i see the below result which is perfect json according to me
[{"Id":4,"Name":"France"},{"Id":3,"Name":"Germany"}]
But in javascript I am getting the json as
[[object Object],[object Object]]
Can anyone please let me know what I am missing here
SOLVED USING
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
There's a few issues with your code. First, despite the fact that you're passing a parameter zone to the web service method the method itself doesn't receive this parameter. Second, if you want to return JSON don't use the return type string. Use JSONResult. This will allow you to remove the static keyword as well. I'd recommend changing your method like so:
public JSONResult GetCountry(int? zone)
{
// ...
}
There are two final changes you should make. The first is to use ASP.Net MVC's built in Json() method to handle serialization of your object. The second is that you should always project your data layer results even if they happen to already be in the structure you want to use. This way if you change your data layer object in a way that breaks the service you'll get a compile error instead of a run time exception.
return Json(from c in Countries.GetAll() select new { Id = c.Id, Name = c.Name })
I'd also recommend avoiding using $.get or $.post as they abstract away settings that can be useful when access web services. If you want to shorthand it I'd recommend wrapping the $.ajax call in your own function. You're also going to want to think about standardizing your web service responses. Your web service is a protocol of sorts and as such it benefits from having a well defined header. For a more in-depth explanation take a look here: Introduction to MVC Service Based Web Applications
try this :
alert(data[0].Name)
$.ajax({
type: 'POST',
url: '../User/GetCountry',
data: {
zone: 1
},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
works good for me. You need to make sure you're sending a content-type of "application/json", preferably using the Json() helper method in Controller.
Solved this after searching bit more
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
Try using JSON.parse():
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
data=JSON.parse(data)
alert(data["Countries"][0].Name);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});
I'm new to Kendo and from several days I'm trying to figure out how to populate kendo grid with search data. My case is the following:
I have javascript viewmodel:
sl.kendo = function () {
var billingReportViewModel = kendo.observable({
billingReportCriteria: [],
executeSearch: function (e) {
var $grid = $("#gridResults").data("kendoGrid");
$grid.dataSource.read();
$grid.refresh();
}
});
return {
billingReportViewModel: billingReportViewModel
}
} ();
And I initialize the billingReportCriteria from the server with this function:
var initCriteriaViewModel = function () {
$.ajax({
url: 'GetBillingReportCriteria',
type: "GET",
dataType: "json",
success: function (model) {
**$.extend(sl.kendo.billingReportViewModel.get("billingReportCriteria"), kendo.observable(model));**
// bind to the viewModel
kendo.bind($("#searchTable"), sl.kendo.billingReportViewModel);
}
});
}()
Than I declare my grid DataSource that sends this billingReportCriteria to the server as parameter:
var gridDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "GetBillingReportResults",
data: JSON.stringify(sl.kendo.billingReportViewModel.get("billingReportCriteria")),
cache: false,
type: "POST"
}
},
schema: {
data: "Items",
total: 10 // total number of data items is returned in the "count" field of the response
}
});
And I init my kendo grid:
$("#gridResults").kendoGrid({
columns: [
{
field: "Name"
},
{
field: "Title"
}],
dataSource: gridDataSource,
autoBind: false
});
When I execute the search from the view model 'executeSearch' I go the server, but the billingReportCriteria is empty! When I check the 'billingReportViewModel' value from F12 Chrome tools everything seems to be OK, but when I check the value of 'sl.kendo.billingReportViewModel.billingReportCriteria' or 'sl.kendo.billingReportViewModel.get("billingReportCriteria")' - it's empty though 'sl.kendo.billingReportViewModel.get("billingReportCriteria.Name")' for example has the right value!
Can you suggest what the problem is? Somehow I can't send the right 'billingReportCriteria' to the server!
I figure out the following thing. When I get the method on the server that is responsible for returning the results the only way I can get the passed parameters is by using the Response.Form or Response.QueryString in the body of the method. How can I pass the arguments to that method so I can get them like this:
public JsonResult GetBillingReportResults(string billingCriteria)
{
string criteria = Request.Form["billingCriteria"]; //I can do it like this, but I want to pass the arguments as method parameters
}
Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).
What I missing about posting to ActionMethods to pull data here ?
I need to do a simple javascript/jquery call to an ActionMethod that will populatel my drop down menu with data from my Json object of type IQueryable ( or List ).
So I tried two options:
function populateuUsers(id) {
$.post("/User/GetUsersJson/", { id: id }, function (data) {
if ($.isEmptyObject(data)) {
alert("Empty");
}
$.each(data, function (item) {
alert(item);
$("#user-list").append(
$("<option></option>").text(data[item].FullName).val(data[item].Id)
);
});
}, "json");
}
I get an error that "data is undefined"
Then I tried:
function populateUsers(id) {
$.ajax({
type: 'post',
datatype: 'json',
url: "/User/GetUsersJson/" + id,
success: function (data) {
alert(data);
$.each(data, function (item) {
alert(item);
$("#users-list").append(
$("<option></option>").text(data[item].FullName).val(data[item].Id));
});
},
error:function()
{
alert(data);
}
});
}
Doesn't work either.
Something to note...I set break points and did verify that data in GetUsersJson Action method User controller gets properly populated and returned to the javascript function.
Why is it not working then ? Why is "data undefined" and it acts like there nothing returned ?
Thank you in advance.
Inside the anonymous function that you're passing to $.each, data is not defined. Instead you should pass two variables to that function. Something like:
$.each(data, function (key, item) {
alert(item);
$("#users-list").append(
$("<option></option>").text(item.FullName).val(item.Id));
});
http://api.jquery.com/jQuery.each/