after typing client name #NAME1 im trying to get this client subaccounts #SUB in list from other table in db, but my list is empty . What im doing wrong?
html
<script type="text/javascript">
var kunnr; var ROLA;
$(document).ready(function () {
$('#NAME1').autocomplete({
source: function (request, response) {
$.ajax({
url: "Form2",
method: 'POST',
data: {
term: $('#NAME1').val()
},
success: function (data) {
response(data);
}});},
select: function (event, ui) {
kunnr = ui.item.kunnr;
}});});
$('#NAME1').change; ({
source: function (request, response) {
$.ajax({
type: "GET",
url: "Form3",
method: 'POST',
data: {
term: $('#SUB').val(), kunnr: kunnr, ROLA:"Slave"
},
success: function (data) {
response(data);
}});}, });
controller
[HttpPost]
public JsonResult Form2(string term)
{
return Json(db.KLIENCI.Where(c => (term!=null && c.NAME1.Contains(term))||(term==null)).OrderBy(x=>x.NAME1).Take(10).Select(a => new { label = a.NAME1,kunnr=a.KUNNR }));
}
[HttpPost]
public JsonResult Form3(string term, string kunnr)
{
return Json(db.CLI2LOGIN.Where(c => ((term != null && c.LOGIN.Contains(term)) || (term == null))&& c.KUNNR== kunnr && c.ROLA == "Slave").OrderBy(x => x.LOGIN).Select(a => new { label = a.LOGIN }).ToList(),JsonRequestBehavior.AllowGet);}
Please find below an example:
View:
<script>
$(document).ready(function () {
$('.maincat').change(function () {
updateSubCategoryList($(this).val());
});
function updateSubCategoryList(catId) {
$('.subcat').empty();
$('.subsubcat').empty();
$.ajax({
url: '#Url.Action("GetSubCategories")',
type: 'Get',
data: { main: catId },
success: function (response) {
var subcat = $('.subcat');
subcat.append('<option value=""></option>');
if (response != null && response != '') {
$.each(response, function (index, value) {
subcat.append('<option value="' + this.SubCategoryID + '">' + this.SubCategoryDescription + '</option>');
});
}
}
});
}
</script>
Controller:
[HttpGet]
public JsonResult GetSubCategories(int main)
{
var i = _jobsservice.GetSubCategories(main);
return Json(i, JsonRequestBehavior.AllowGet);
}
Related
Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
},
submitHandler: function (form) {
var form_data = $(form).serialize();
console.log(form_data);
$.ajax({
type: 'post',
url: SITE_URL+url,
data: form_data,
success: (function (json) {
if (json.type == "success") {
$.each(json, function(i, item) {
$('#div1').append("value"+item.name+) ;
})
var type = 'Created';
if(json.value===1 && typeof json.value != 'undefined'){
type = 'Update';
}
//$("#showDetail form").append();
resetform($(form).attr('id'));
successMessage('Subscription '+type+' Successfuly');
getPosts('show='+$('.custome-show-option select').val()+'&page='+$('#PcurrentPage').text());
} else {
$("#error_div").html('Module already exist');
}
}),
error: (function (response) {
$("#error_div").html('Error in processing');
})
});
this code is proper work but not show append data of form data where success::function(json) {} where j console.log(json) show output only 1
I don't know what is actually your problem but:
in your javascript code you should add:
dataType:'json'
In laravel in controller you should have something like this:
return response()->json(['type' => 'success', 'value' => 1, 'items' => $arrayOfItems]);
This part should be something like this:
$.each(json.items, function(i, item) {
$('#div1').append("value" + item.name) ;
});
I am trying to implement the jQuery autocomplete. I feel like everything is set up just fine, however It's not working.
SearchSkies method
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
The script in View
<script type="text/javascript">
$( function() {
$( "#searchBox" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: '#Url.Action("SearchSkies","Skies")',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
}
} );
},
minLength: 2,
});
});
</script>
You are not mentioning type of request(GET/POST) in ajax call.
$(document).ready(function () {
$("#searchBox").autocomplete({
source: function(request,response) {
$.ajax({
url: "/Skies/SearchSkies",
type: "POST", <<----
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
And the controller
public class SkiesController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
}
I am using MVC. In my one page, if i type one value that is process, if it exists the related details will populate in other all fields. how to do this in Ajax call?
Controller:
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return View("Call",partner);
}
Call is the Aspx page.
In view:
<script type ="text/javascript">
$('#getPincode').text('Get Pincode') // Sets text for company.
.attr('href', '#');
$("#getPincode").click(function () {
$('#getPincode').text('Get Company')
.attr('href', 'GetDetail?pincode=' + $('#Pincode').val());
});
$("#Pincode").blur(function () {
$("#checkPincode").trigger('click');
});
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
But i don't know how to populate the result into my view which means editor fields???
View:
<%:Html.TextBox("Address")%>
You can try this one:
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = {'pincode': name};
$.ajax({
type: "POST",
url: "/GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
return it as a jsonResult
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner);
}
or if you want to load partial view load it as
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return PartialView("Call",partner);
}
<div id="myDiv"></div>
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
$('#myDiv').html(data);
}
});
return false
});
});
I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^