AutoComplete inside keyup jquery weird behaviour - javascript

I've a conditional ajax function call. On receiving response, data is binded to the autocomplete. The problem is that, on entering first key, Autocomplete list doesn't shows up even though it has values binded to it. The list shows up only after entering the subsequent letter(s).
$("#AutoComplete").on('keyup', function (event)
{
if ($("#AutoComplete").val().length <= 5 )
{
GetData();
}
});
function GetData()
{
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: '{"key":"' + $("#AutoComplete").val() + '"}',
dataType: "json",
success: function (data)
{
var output= $.map(data, function (item)
{
return {
label: item.Name,
value: item.ID
};
});
$("#AutoComplete").autocomplete({
source: output,
autoFocus: true,
});
}
});
}

Consider the following example.
$("#AutoComplete").autocomplete({
source: function(req, resp) {
if (req.term.length <= 5) {
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: {
key: req.term
},
dataType: "json",
success: function(data) {
var output = $.map(data, function(item) {
return {
label: item.Name,
value: item.ID
};
});
resp(output);
}
});
}
},
autoFocus: true,
});
You can use a Function for the Source:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
https://api.jqueryui.com/autocomplete/#option-source

Related

how get data ajax api array using javascript / jQuery?

how to get data from list api using javascript? i have api with list use json data.. but i'm stuck when get data from list number one. what must i do with this case?
{
"idMaster": "10",
"data": [
{
"id": "20",
"rateBPK": 3,
"updatedBy": "System"
},
{
"id": "30",
"rateBPK": 4,
"updatedBy": "System"
}
]
}
this my code, but i can't return data
var dataBKP;
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
cache: false,
url: '#Url.Action("GetBpkOtrAsync", "SimulasiKredit")',
data: JSON.stringify(param),
success: function (Data, textStatus, jqXHR) {
$.each(Data.data, function (i, rowData) {
dataBKP = Number(rowData.rateBPK);
});
},
return dataBKP;
});
Firstly, there appears to be a couple syntax errors in your code near the bottom. I don't think you've closed the $.ajax() call, nor the object inside of it.
Secondly, it appears as though you are trying to return dataBKP after the success function fires, however you've written it outside of your success function.
The success callback runs asynchronously, and therefore after ajax has completed. The return statement here will fire before success has a chance to run in most circumstances.
The solution would be to move it into the success function:
var dataBKP;
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
cache: false,
url: '#Url.Action("GetBpkOtrAsync", "SimulasiKredit")',
data: JSON.stringify(param),
success: function (Data, textStatus, jqXHR) {
$.each(Data.data, function (i, rowData) {
dataBKP = Number(rowData.rateBPK);
});
return dataBKP;
}
});
You might find it easier to track which functions you've closed if you add spacing inside the nested components, as well, so you don't end up with }}); at the end.
Lastly, you're running an .each loop over your data, however overwriting the dataBKP var on each pass. I would recommend either concatenation, summation, or pushing into an array. (dataBKP = dataBKP + Number(rowData.rateBPK);, for example).
EDIT: after seeing you make a couple changes, I'm guessing your post is still in flux. If so, then you may already know all the things I've listed above and you're trying to correct them. In that case, I want to add that you are probably going to bump into a couple things:
First, you're returning the dataBKP var, instead of using it. This is kind of a confusing topic since they load asynchronously, but you are probably returning it to nowhere. The success function is a void function. Instead, try logging the success function so you can see it appearing later and get an understanding of how this works.
Next, dataBKP being set will be hard to play with because of scope.
Add a function that the success action can call so that your code can use the dataBKP var. And then, consider passing it in so that function can be reused later. And then pass the value, rather than directly calling the variable. Like so:
var dataBKP = 0;
var functionToManipulateThatDataAfterAjaxCall = function(data) {
// do something with your data here
console.log("Called from within the success callback: " + dataBKP);
};
console.log("Just before the success callback: " + dataBKP);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
cache: false,
url: '#Url.Action("GetBpkOtrAsync", "SimulasiKredit")',
data: JSON.stringify(param),
success: function (Data, textStatus, jqXHR) {
$.each(Data.data, function (i, rowData) {
dataBKP = Number(rowData.rateBPK);
});
console.log("Inside the success callback: " + dataBKP);
functionToManipulateThatDataAfterAjaxCall(dataBKP);
}
});
console.log("Just after the success callback: " + dataBKP);

How do I pass parameter data to a controller in mvc from an Kendo Grid event?

I want to pass a lot of parameters from my ajax function to my controller. Initially, I thought I would just do this using a query string but that wasn't giving me the result I wanted, although it worked it was creating an unattractive URL the more data I added.
I thought the better approach would be to take all this data I need to pass, store it as an object and pass that payload into the controller from an ajax function.
The ajax function is triggered from the .event() attribute of the KendoGrid.
Kendo Grid
#(Html.Kendo().Grid<MyProject.Models.Car>()
.Name("requirement-grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Command(command => command
.Custom("Test").Click("payload"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetCars", "cars"))))
As you can see from the above code, there is a custom command that I've used which triggers a function when you click on it. The function is payload and the code is as follows:
payload
function payload(e) {
e.preventDefault();
//Get row data
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Create Object
var obj = {
Name: dataItem.Name,
BHP: dataItem.BHP,
YearOfBuild: dataItem.YearOfBuild
}
//Post via Ajax
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
}
I access the data of the row that was clicked on and pass it down via the events parameter, from there I create an object and add the data to it. I then create an ajax call and try to pass it to the controllers.
The controller expects the parameter, the code is as follows but shortened for brevity.
Controller
public ActionResult Create(object[] obj)
{
return View(obj);
}
If I use "POST" in my ajax function I get an error regarding a anti-forgery token which is missing. If I use "GET" the obj parameter is always null.
The required anti-forgery cookie "__RequestVerificationToken" is not present.
Is there a better way to be doing this or is my approach incorrect?
So this should be a relatively simple change to your code. I am assuming you have an anti-forgery token loaded onto the page and the action you are posting to is protected by this. You have two solutions here:
1) Remove the requirement for the token if it isn't needed from the action in your controller
2) Provide the token as part of the data package you are sending back to the server by changing your code from
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
to:
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: {
array: JSON.stringify(obj),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("Success");
},
error: function(ob, errStr) {
console.log(ob.responseText);
}
});
Notice I have just added a reference to the anti-forgery token as part of the data package for you and this should be read by the controller and allow the command to complete successfully for you if you have the token on the page. if not then just add the #Html.AntiForgeryToken() to the view and you should be fine.

Laravel 5.2 with Select2 v 3.5.1 ajax method POST, token mismatch

I am trying to use Select2 using type: POST and try to pass the token through headers just like ajax request. But I got TokenMismatchException.
But I've already tried use Select2 using GET and it works fine.
Is it possible to use Select2 with type POST or just GET?
Here is my code
var token = '{{csrf_token()}}';
$(".eta").select2({
placeholder: "Search for source",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: '{{route("part", "source")}}',
dataType: 'json',
type: 'post',
headers: {
'X-CSRF-TOKEN': token
},
quietMillis: 250,
data: function (term, page) {
return {
q: term, // search term
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
console.log(data);
dataSourceParts = [];
$.each(data, function(key, val) {
dataSourceParts.push({
id: val.id,
text: val.name+'-'+val.code
});
});
// since we are using custom formatting functions we do not need to alter the remote JSON data
return { results: dataSourceParts };
},
cache: true
},
});

jQuery .ajax call never calling method

In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.

calling method in javascript, but error throws?

I need to call ajax method couple of places. So want to try to minimize the code by creating separate method for it. If use directly, it works perfect. but when I separate it won't work.
data: columns[5],
type: 'autocomplete',
options: { items: 100 },
source: function (query, process) {
$.ajax({
url: "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},
strict: true
}
it doesn't work, if I call this way. It says Microsoft JScript runtime error: 'query' is undefined, how to fix it?
{
data: columns[4],
type: 'autocomplete',
options: { items: 100 },
source: callAutoCompleteAjaxMethod(query, process, "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()),
strict: true
},
callAutoCompleteAjaxMethod = function (query, process, url) {
$.ajax({
url:url,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},
You call
source: callAutoCompleteAjaxMethod(query, ...
But you never gave 'query' a value, give it a value and it will work.
You are calling the function instead of assigning it to the source property. And at this moment the variable query is not defined.
You have to assign a function, so that the plugin can call it later:
source: function (query, process) {
callAutoCompleteAjaxMethod(
query,
process,
"/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()
);
}
(I hope $value is defined somewhere)
Parenthesis ( () ) after a function reference always calls the function immediately. If you want to pass a reference to the function, you don't put parenthesis after it.

Categories