JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local - ajax

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Related

Kendo Treeview expand and checkbox not working after new value was passed in from a dropdown list

new to stackoverflow and implementing treeview. I'm having an issue where whenever I select a different value from my dropdown list that would populate my treeview the expand and checkbox is not working anymore. But the first time works.
So I have ajax call that would grab a parameter from a dropdown list to return JSON data to populate my tree. Here's my code. I've been pounding my head for this error and I've also tried some solution in the kendo ui documentation but it just doesn't work. Really need some help. Thank you!
Here's my code:
dataB1 = #Html.Raw(Json.Encode(ViewData["branchList"]));
reloadNewBranch = #Html.Raw(Json.Encode(ViewData["reloadNewBranch"]));
$('#comboNewBranch').kendoAutoComplete({
dataSource: dataB2,
placeholder: "Enter branch name...",
value: reloadNewBranch
});
//Create TreeView
function onChange(e) {
$("body").css("cursor", "progress");
$('#hiddenPackageArray').val('');
document.getElementById("textTestpassId").innerHTML = 'At least one(1) template must be selected.';
$('#treeview').empty();
$.ajax({
url: '#Url.Action("LoadOldBranchTemplates", "Home")',
data: { oldBranchName: $("#comboOldBranch").data("kendoAutoComplete").value() },
dataType: "json"
}).done(function (result, textStatus, jqXHR) {
var viewModel = new kendo.data.HierarchicalDataSource({
data: result,
schema: {
model: {
id: "Id",
hasChildren: true,
children: "Templates"
}
}
});
$("#treeview").kendoTreeView({
loadOnDemand: false,
checkboxes: {
checkChildren: true
},
check: onCheck,
dataSource: viewModel,
dataTextField: ["TestPassName", "DisplayName"]
})
// gathers IDs of checked nodes
function checkedNodeIds(nodes, checkedNodes) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].Id);
let filtered = checkedNodes.filter(function (listOfId) {
return listOfId != null;
});
$('#hiddenPackageArray').val(filtered);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
// show checked node IDs on datasource change
function onCheck(e) {
console.log("I'm in onSelect function");
var checkedNodes = Array();
var treeView = $("#treeview").data("kendoTreeView");
var message = String();
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
console.log("Checkbox changed :: " + this.text(e.node));
if (checkedNodes.length > 0) {
message = checkedNodes.join(" ");
} else {
message = "No package(s) are selected.";
$('#hiddenPackageArray').val('');
}
$("#result").html(message);
}
$("body").css("cursor", "default");
})
.fail(function (xmlHttpRequest, textStatus, errorThrown) {
$('#mainDiv').append('<p>Status: ' + textStatus + '</p>');
$('#mainDiv').append('<p>Error: ' + errorThrown + '</p>');
$('#mainDiv').append('<p>' + xmlHttpRequest + '</p>');
});
};

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

Converting MVC Ajax to Jquery

I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});

Jquery UI Autocomplete Ajax JSONP return is broken in JQ UI Version 1.8.6

Ive been using the code below for my auto-completes on my form for a while , but after updating jquery ui to version 1.8.6 from 1.8rc3 it has broken the formatting of the JSONP return. The returned data is no longer formatted html, but instead it is a string. Any Ideas?
Update: JS Fiddle included, using the jquery ui demo and html in the data
http://jsfiddle.net/blowsie/ejLPg/
$("#companyname").autocomplete({
source: function (request, response) {
$.ajax({
url: turl,
dataType: "jsonp",
data: {
maxRows: 9,
name_startsWith: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: "<span class='ui-menu-item-title'>" + item.name.toLowerCase() + "</span><span class='ui-menu-item-subtitle'>" + item.address1.toLowerCase() + ' ' + item.post_code.toLowerCase() + '</span>',
value: item.name_id
}
}))
}
})
},
minLength: 3,
delay: 50,
select: function (event, ui) {
LoadGivenCompany(ui.item.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
focus: function () { return false }
});
Thanks in advance
I looked into the source code of autocomplete of version 1.8.6 and found out that item creation uses text method instead of the html method. They suggest at jQuery.ui to change style using the theme roller of by altering the widget specific classes in the css file.
See Autocomplete#theming.
What i would do is find the place that they push the text in the element and change the method call back to html and test it out.
Turns out by using the .data(), after the autocomplete allows you to format the data
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.geonames, function(item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name,
test: 'hahahah'
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.test + "</a>" )
.appendTo( ul );
};
});
http://jsfiddle.net/blowsie/ejLPg/3

jQuery DoubleSelect/Cascade/Dependent/WalkRight Select Menus w/ Ajax Support?

Where you can pick an item from a <select> menu and then it populates a second <select> menu.
It goes by too many names and there are too many implementations. I'm looking for an up-to-date one (works well with the latest version of jQuery) that can pull the data using Ajax.
Can anyone recommend a good plugin?
// simple code but can be improved for need
function getListBoxValue(obj) {
obj = $.extend({
url: "",
bindObj: null,
emptyText: "exception",
postValues : {},
onComplete: function () { return true; },
onError: function () { return false; }
}, obj);
$.ajax({
url: obj.url,
data: obj.postValues,
type: "POST",
dataType: "JSON",
success: function (json) {
var options;
$.each(json, function (i, e) {
options += "<option value='" + e.Value + "'>" + e.Text + "</option>";
});
$(obj.bindObj).html(options);
obj.onComplete(obj);
},
error: function (e, xhr) {
$(obj.bindObj).html("<option value='-1'>" + obj.emptyText + "</option>");
obj.onError(obj);
}
});
}
// server response data json
[{ "Value": 1, "Text": "text 1 " },{ "Value": 2, "Text": "text 2"}]
getListBoxValue({
url: responseJsonDataURL, // example
bindObj: $("select#YourID"), // example
emptyText:"exception text", // example
postValues: {"id": 45}, // example
onComplete: _onCompleteFunction, // optional
onError: _onErrorFunction // optional
})

Resources