jquery autocomplete is now working properly - ajax

I am working on jquery autocomplete in mvc platform. Now, my question is that in some textbox data autocomplete is working properly while in some textbox data autocomplete is not working properly.
For more clear, lets see the image of autocomplete task
now as per the image when I write the R word, I am getting the suggestion list of related R word.
now as per the second image I have written the whole word but still suggestion is not display.
Here is my code,
View
<input type="text" id="CustomerName" name="CustomerName" required data-provide="typeahead" class="typeahead search-query form-control autocomplete"
placeholder="Customer Name" />
<script>
$(document).ready(function () {
$.ajax({
url: "/ServiceJob/CustomerSerchAutoComplete",
method: "GET",
dataType: "json",
minLength: 2,
multiple: true,
success: function (data) {
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
//autocomplete(document.getElementById("CustomerName"), data.data);
$('#CustomerName').autocomplete({ source: data.data, minLength: 2, multiple: true });
}
});
});
</script>
Controller
[HttpGet]
public IActionResult CustomerSerchAutoComplete()
{
var customers = _Db.Ledger.Where(x => x.LedgerTypeId == (int)LedgerType.Customer).ToList();
var result = (from n in customers
select new
{
kk = n.Name.ToUpper()
}).ToList();
return Json(new { data = result });
}

As you are getting
Uncaught TypeError: Cannot read property 'substr' of undefined
For this error you should check that data is not null.
success: function (data) {
if(data != null)
{
autocomplete(document.getElementById("CustomerName"), data.data);
}
}

Related

Asp.net core controller function with return partial view with select2 not working and remote function validation is not firing in modal popup

Select2 is not working and remote validation is not firing, this is only happens when I convert the code to modal popup but if not everything is working properly. What Am I missing in my code? Any advise or help much appreciated.. Thank you
Here is my code the modal:
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
$('#EditUnitModal').modal()
}
});
});
Here is the controller edit code:
public async Task<IActionResult> Edit(int? id)
{
//code here
return PartialView("__Edit", product);
}
And here is my partial view __Edit code:
#model intPOS.Models.Master.ViewModel.ProductViewModel
//code here
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#Unit').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
$('#Category').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
})
</script>
}
And View model code:
[Display(Name = "Product Code"), Required]
[Remote("CheckProduct", "Products", AdditionalFields = "Id", ErrorMessage = "Product already exists.")]
public string ProductCode
{
get
{
return _productcode;
}
set
{
_productcode = value.Trim();
}
}
Sample screen for not firing validation and select2 is not working:
sections aren't allowed in partial views. You can still use modals and partial views via Ajax for edit forms but there is a small modification you need to do in order for this to work:
Include all the necessary scripts in your page (this is mandatory as sections aren't allowed in partial views).
In your javascript code add these lines in order to parse the new form via jquery validation unobtrusive and your select elements via Select2.
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
//Here we parse the new form via jquery validation unobtrusive.
$.validator.unobtrusive.parse($('#EditUnitModal .modal-content form')[0]);
//Here we initialize select2 for the selected elements.
$(".yourSelect2ElementClass").select2({//options...});
//Now we launch the modal.
$('#EditUnitModal').modal()
}
});
});
Don't forget to remove the section from your partial view and include your scripts in the containing view.

Make 2 AJAX calls on button Click

I am working on ASP.NET MVC project. In my home page, I have a search box with a search button.
When User types a Keyword and Click Search, I need to perform 2 independent search Operations (I am using Elasticseach, so two calls to Elasticsearch).
Make a call to SearchItems action method, which will go and get Items from Elasticsearch and returns ItemsPartialView.
Make a call to SearchCategory action method which goes and gets categories from Elasticsearch and returns CategoryPartialView.
In my home page, I want to make 2 ajax calls, to these action methods using AJAX, to display the result.
This Image explains what I want to achieve
Question: Is it possible to make 2 calls to 2 action methods on one event using AJAX?
It's possible. The only real issue is whether you want the ajax requests to be sent in a certain order (and the usual issues of efficiency of code to avoid repeats, the format of the data returned etc). One way of doing this (where the ajax second call is made after the first completes successfully) is sketched out:
<input type="text" id="search-query" value="" />
<button id="test-button">Test Ajax</button>
<div id="ajax-one-result"></div>
<div id="ajax-two-result"></div>
<script>
$(function(){
$(document).on("click", "#test-button", function(){
var qry = $("#search-query").val();
func1(qry);
function func1(queryString) {
var urlOne = "/Path/To/AjaxOne";
return $.ajax({
type: "GET",
url: urlOne,
timeout: 30000,
data: { query: queryString },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-one-result").html(transport);
func2(transport);
console.log("AjaxOne success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxOne");
},
complete: function () {
}
});
}
function func2 (ajaxOneResult) {
var urlTwo = "/Path/To/AjaxTwo";
$.ajax({
type: "GET",
url: urlTwo,
timeout: 30000,
data: { query: ajaxOneResult },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-two-result").html(transport);
console.log("AjaxTwo success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxTwo");
},
complete: function () {
}
});
}
});
});
</script>
with Controller Actions:
public async Task<JsonResult> AjaxOne(string query)
{
// For testing only
System.Threading.Thread.Sleep(5000);
var result = "AjaxOne Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> AjaxTwo(string query)
{
// For testing only
System.Threading.Thread.Sleep(2000);
var result = "AjaxTwo Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}

Ajax post executed twice and adding up

I'm facing an issue with ajax that several users here also encountered but the proposed solution do not seem to work for my case.
in my index.php file, I have:
<pre>
<script>
function ButtonManager()
{
$( "button" ).click(function()
{
var context = $(this).attr('type');
var page_type = $(this).attr('page');
var referrer = $(this).attr('referrer');
var form_type = $(this).attr('form');
var object_id = $(this).attr('object');
var postData = 'page_type='+page_type+'&form_type='+form_type+'&referrer='+referrer+'&id='+object_id;
$( '#indicator' ).css( "display", "block" );
if (context == 'post_form')
{
var formData = $('#submit_content').serialize();
postData = postData+'&context=post_form&'+formData;
}
if ((context == 'load_form') || (context == 'filter_form'))
{
postData = postData +'&context=load_form';
if (context == 'filter_form')
{
var filter1 = $('select[name=filter1]').val();
var filter2 = $('select[name=filter2]').val();
var filter3 = $('select[name=filter3]').val();
postData = postData + '&filter1='+filter1+'&filter2='+filter2+'&filter3='+filter3;
}
}
$.ajax
({
type: 'POST',
url: 'php/sl.php',
data: postData,
cache: false,
async: false,
dataType: 'html',
success: function(result)
{
ManageLayer(form_type+'_content');
$('#'+form_type+'_content').html(result);
$( '#indicator' ).css( "display", "none" );
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
$( '#indicator' ).css( "display", "none" );
},
});
});
}
</script>
<button type="load_form" page="home" referrer="navigation" form="edit" object="">test</button>
</pre>
when a click on the test button, the script calls sl.php to retrieve some html with other buttons in it.
in the output I get from the server I have added:
<pre>
<script>
var myvar=ButtonManager();
</script>
<button type="post_form" page="home" referrer="navigation" form="edit" object="">test2</button>
</pre>
The goal of the ButtonManager function is to manage all my buttons in one function so it needs to be available/known everywhere (in index.php where it's loaded and in all the output I can get from sl.php).
I have added the var myvar=ButtonManager() line because it's the only way I have found to make sure the function is known by the server output. The drawback is that the function is executed multiple times instead of one even if I don't click on the test2 button.
So I'm looking either for a way to prevent my function from being executed multiple times or an alternative to make the function available everywhere.
I don't know what approach would be the best, I'm a casual developper programming for fun and javascript / ajax is not the language I know the best.
Thanks
Laurent
I got the answer from another forum but I wanted to share it in case others are having the same problem.
Code to be used should be like this:
<pre>
$( document ).on("click", "button", function() {
</pre>
It makes the function available to objects that do not exist yet.

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Resources