I am new to Jquery world.
I have these following codes:
$target.ajaxChosen({
type: 'GET',
url: '<s:url action="getFilterValueJSON" namespace="/cMIS/timetable"></s:url>?filterKey='+keyword,
dataType: 'json',
jsonTermKey: 'filterWord'
}, function (data) {
var terms = [];
mydata = data.valueMap;
$.each(mydata, function (i, val) {
terms.push({ value: i, text: val });
});
return terms;
});
It seems the variable 'keyword' does not dynamically changed its value. The value for 'keyword' comes from an element with on change event. Would someone enlighten me about this on how to solve this? Thanks in advance.
its better you compose your url object just before call
function onclick(keyword)
{
var url = '<s:url action="getFilterValueJSON" namespace="/cMIS/timetable"></s:url>?
filterKey='+keyword;
ajaxCall(url);
}
function ajaxCall(url)
{
$target.ajaxChosen({
type: 'GET',
url: url,
dataType: 'json',
jsonTermKey: 'filterWord'
}, function (data) {
var terms = [];
mydata = data.valueMap;
$.each(mydata, function (i, val) {
terms.push({ value: i, text: val });
});
return terms;
});
}
Related
I tried to create Autocomplete using jQuery Ajax. Basically, I want to make autocomplete search with dynamic field added. But while I type in the input field then it gave me this error.
JS Code
$(document).ready(function() {
var arrayReturn = []
$.ajax({
url: "/suppliers",
async: true,
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.length; i++) {
var id = (data[i].id).toString();
arrayReturn.push({'value' : data[i].name, 'data' : id})
}
printSupplier(arrayReturn);
}
});
function printSupplier(suppliers) {
$('#purchase_item_search').autocomplete({
lookup: suppliers,
onSelect: function (result) {
$('#autocom-box').html(result.value);
}
});
}
});
Problem Solved.
$(document).ready(function() {
$("#purchase_item_search").on('keyup', function() {
var arrayReturn = []
$.ajax({
url: "/suppliers",
dataType: 'json',
success: function(data) {
// console.log(data['suppliers'].length);
for (var i = 0; i < data['suppliers'].length; i++) {
var id = (data['suppliers'][i].id).toString();
arrayReturn.push({
'value': data['suppliers'][i].name,
'data': id
})
}
printSupplier(arrayReturn);
}
});
function printSupplier(options) {
$('#purchase_item_search').autocomplete({
source: options,
onSelect: function(result) {
// $('#autocom-box').html(result.value);
console.log(result);
}
});
}
});
});
I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.
I have a view model in knockout as follow. What i intend to achieve here is to make the ajax call into a reusable function as follow (and include it into separate js file).
However, I got the error message showing self.CountryList is not defined. How could this be resolved?
// Working
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
self.CountryList.push(value);
});
}
});
}
}
ko.applyBindings(new LoadCountry());
// Not working
function LoadCountryList() {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
self.CountryList.push(value);
});
}
});
}
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
LoadCountryList();
}
}
ko.applyBindings(new LoadCountry());
Your LoadCountryList function in the second version has no concept of the object it should be operating on - ie it has no idea what self is, hence the error. The simple solution is for you to pass the object in when calling the function:
function LoadCountryList(vm) {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
//reference the parameter passed to the function
vm.CountryList.push(value);
});
}
});
}
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
//pass ourselves to the function
LoadCountryList(self);
}
}
well clearly self.ContryList does not exist in your external file. One easy way to solve this is to pass in a reference to the appropriate "list" to push values to:
function LoadCountryList(countryList) {
$.ajax({
url: '/api/MyApi',
type: 'GET',
dataType: 'json',
success(data): {
$.each(data, function (index, value) {
countryList.push(value);
});
}
});
}
and in your view model:
var ViewModel = function() {
var self = this;
self.CountryList = ko.observableArray([]);
self.LoadCountry = function() {
LoadCountryList(self.CountryList);
}
}
I'm almost there and on my first jquery autocomplete script... I just need some help to figure out how to return the founded elements has link so that we can click on them.
Here a part of my js code:
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: request.term},
success: function(data) {
searchRequest = null;
console.log(data);
$.each(data, function (i, v) {
--- SOME VARIABLE I GUESS TO STORE THE RESULT ---
});
return THE 'SOME VARIABLE;
}
}).fail(function() {
searchRequest = null;
});
}
});
});
In the console I got this from the console.log(data) line:
Object {École secondaire De Rochebelle: "/GestigrisC/app_dev.php/lieux/voir/2", École secondaire la Camaradière: "/GestigrisC/app_dev.php/lieux/voir/3"}
I have control over how the JSON feed is built, so no worries there if it's helps to build that super mysterious for me now variable to return.
Thanks a lot for the help!
If you just want to build links and put them into your HTML then I think you're looking for something like this:
success: function(data) {
var html = '';
$.each(data, function (i, v) {
html += ''+i+'';
});
$('#container_id').html(html);
}
Got it right, thanks for your help :)
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(requete, reponse) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: requete.term},
success : function(donnee){
reponse($.map(donnee, function(objet){
return {label: objet.type + ' | ' + objet.label, type: objet.type, id: objet.id};
}));
}
}).fail(function() {
searchRequest = null;
});
},
select: function (event, ui) {
$('#leseulsteve_lieuxbundle_lieutype_nom').val(ui.item.label);
$('#leseulsteve_lieuxbundle_lieutype_type').val(ui.item.type);
$('#leseulsteve_lieuxbundle_lieutype_id').val(ui.item.id);
$('#formulaire').submit();
}
});
});
I hava a common ajax.post method which accepts data from function parameter. Now i want to trim the properties of data. Below is the code.
function PostToServer(options) {
var defaults = {
'url': null,
'data': null,
'onSuccess': null,
'onError': null
};
var parameters = $.extend(defaults, options);
$.ajax({
url: parameters.url,
type: "POST",
data: JSON.stringify(parameters.data),
contentType: "application/json",
success: function (res) {
if ($.isFunction(parameters.onSuccess)) {
parameters.onSuccess(res);
}
},
error: function (xhr, status, error) {
if ($.isFunction(parameters.onError)) {
parameters.onError(xhr, status, error);
}
}
});
}
Now in this function i want to trim the 'parameters.data' object so that it removes whitespace from both ends. but i dont know what comes in 'parameters.data' so i can not access its properties and use trim function.
Please help.
Try this:
$.each(res, function(index) {
var that = this;
$.each(that, function(key, value) {
var newKey = $.trim(key);
if (typeof value === 'string')
{
that[newKey] = $.trim(value);
}
if (newKey !== key) {
delete that[key];
}
});
});