JQuery AutoComplete with JSON Result Not Working - javascript

I am using a JQuery autocomplete to display a list of available courses. I am doing a post to get a list of Courses from the server, I manipulate the data to be in the expected format, and I pass it to the autocomplete function. The problem is that it does not work unless I hard copy and paste the values newSource and paste them into source.
The variable newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc].
The ajax post to get the data from the server
//Auto complete for search box
$('#AdditionalSearch').on('input', function () {
var source = [];
var inputValue = $('#AdditionalSearch').val();
if (inputValue !== '') { //the value is not empty, we'll do a post to get the data.
url = "/Course/CourseSearch";
$.ajax({
method: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
data: JSON.stringify({ "searchCourseValue": inputValue }),
url: url,
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = '[';
$.each(myData.ResultValue, function (index, item) {
if ((myData.ResultValue.length -1) == index)
newSource += '"' + item.Name+'"';
else
newSource += '"'+ item.Name + '",';
});
newSource += "]";
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
error: function (jqXHR) {
console.log(error);
}
});
} else { //The user either delete all the input or there is nothing in the search box.
//The value is empty, so clear the listbox.
setNameAutoComplete(source);
}
});
//Passing the source to the auto complete function
var setNameAutoComplete = function (data) {
console.log(data);
$('#AdditionalSearch').autocomplete({
source: data
});
}
Is there something that I am missing here?

When you literally paste newSource = ["Enc1001","ENC1002","Enc1003","ENC1101"....etc]in your code, you are building an array object. However, in your success method, you are building a string (the string-representation of that same object). What you want to be doing is build an actual array in stead.
...
success: function (data) {
if (data.Ok) {
var myData = JSON.parse(data.data);
var newSource = [];
$.each(myData.ResultValue, function (index, item) {
newSource.push(item.Name);
});
console.log(newSource);
source = newSource;
}
setNameAutoComplete(source);
},
...

Related

"Error : Cannot use 'in' operator to search for 'length' in [{"ID":"2","Name":"EAA2"}]" when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]
I split it into two functions as I didn't want to keep going back to the api everytime a user selects/de-selects an option.
I have also tried the following:
Changing vars to lets
Passing data.d from the update to the populate
function populateAvailableAuthorities() {
var list = $('#availableAA');
var data = JSON.parse($('#AAJSON').val());
var auths = $('#tbSelectedAA').val();
list.empty();
$.each(data, function (key, entry) {
if (!~auths.indexOf(entry.ID + ';')) {
list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
}
});
}
function updateListboxes() {
var teams = '';
let aa = $('#AAJSON');
aa.empty();
$('#cblTeams input:checked').each(function () {
teams += $(this).attr('value') + ',';
});
if (teams.length > 1) {
teams = teams.substr(0, teams.length - 1);
$.ajax({
type: "POST",
url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
data: '{teams: "' + teams + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
aa.val(JSON.stringify(data.d));
populateAvailableAuthorities();
}
});
}
}
It would seem that "over-stringifying" is an issue with JSON. If I doubled the JSON.parse or removed the JSON.stringify it all works correctly.
Annoying!!

array is empty even if it was successfully mapped

I'm running into issues with _.map (using underscore.jshttp://underscorejs.org).
getCalories: function() {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
_.map(ingArray, function(elem)
{
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem,
complete: function(r) {
var obj = JSON.parse(r.responseText);
var calorie = obj.calories;
calArray.push(calorie);
console.log(calArray);
}
});
});
},
I need to use the latest iteration of calArray in another function. However, it always comes up as undefined. So I inserted a console.log above and this is what I get:
app.js:177 is the console.log
Is this a scoping issue? Also, if it's logging prior to the push then I can see why it's coming up as undefined. How do I get around it?
I believe underscore's map produces a new array, in your case the new array will contain a bunch promises (ajax-requests)
You may want to assign this to a variable first, something like below:
getCalories: function () {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
var requests = _.map(ingArray, function(elem) {
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem
});
});
$.when.apply($, requests).then(function(results) {
console.log(results); // can you take a screenshot of this output
var calories = _.map(results, function(result) {
return JSON.parse(result.responseText).calories;
});
calArray = calArray.concat(calories);
});
}

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Add Property dynamically to the JSON array

I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller
With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png

Only 1 result from JSON loop

Could somebody explain how come this is only returning 1 result (there should be 4). Its only returning the most recent post title, where I would like to be getting all the post titles in the category (ID: 121) which in this case is four.
<script type="text/javascript">
var posturl = "http://www.tropical420.com/api/get_posts/?posts_per_page=-1";
$.ajax({
type: 'GET',
url: posturl,
complete: function(){
},
success: function (data) {
var response = data; //JSON.parse(data);
//loop through posts
for(var i = 0; i != response.posts.length; i++) {
//get each element in the array
var post = response.posts[i];
// post vars
var postTitle = post.title;
var postContent = post.content;
var postCategory = post.categories[i].id;
// output stuff so we can see things
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
</script>
<div id="post"></div>
The problem you have is that you aren't iterating through all the categories, instead you are just referring with the same index as to your posts array. You should iterate all the categories through like this
var postCategories= post.categories;
for (var postCategoryIndex in postCategories)
{
var postCategory = postCategories[postCategoryIndex].id;
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
The JSON returned does indeed include 49 posts, and you would know that if you had tried console.log(response.posts.length)
sanfor has pointed out the logic error in your code, but your whole callback function can be written much more cleanly, like this:
function (data) {
data.posts.filter(function (post) {
return post.categories.filter(function (cat) { return cat.id === '121'; });
}).forEach(function (post) {
$("#post").append(post.title + "<br />").trigger('create');
});
}

Categories

Resources