SELECT2 ajax - preloaded options - ajax

At the moment I have a dropdown that works with ajax request to the server, but it also be nice to attach some default options on select2 initialization. With initSelection function I only can attach one option, but not full preloaded array. I was also trying to use data option but it's doesn't work too.
Here is my code:
$("#address-select2").select2({
placeholder: "--- ' . t('I\'ll add new address') . ' ---",
minimumInputLength: 3,
ajax: {
url: "/ajax/address_autocomplete/from",
dataType: "json",
type: "POST",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {results: data.addresses};
}
},
initSelection: function (element, callback) {
$.ajax("/ajax/address_autocomplete/from/100", {
dataType: "json"
}).done(function(data) {
callback(data.addresses[0]);
});
},
formatResult: function (address) {
return "<span class=\"dropdown-element\">" + address.text + "</span>";
},
formatSelection: function (address) {
return address.text;
},
formatNoMatches: function () { return "' . t('No result found!') . '";},
formatSearching: function () { return "' . t('Searching...') . '"; },
formatLoadMore: function (pageNumber) { return "' . t('Loading results...') . '"; },
dropdownCssClass : "bigdrop"
});

please do not pass callback(data.addresses[0]);
please pass array directly like this callback(data.addresses);
it should work i have done it.

Related

Ajax - Parse oData Response

I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)

Syntax Error JSON file read with AJAX

I am getting a syntax error for the square bracket '[' from my JSON file. Given below is the JSON.
[
{
"Product Name":"CPE 10281",
"Application":"Tyres",
"Weight":150,
"Cost to Produce":5000,
"Grade":"A",
"Cost to Sell":40000,
"Strength":100
},
{
"Product Name":"CPE 10282",
"Application":"computers",
"Weight":250,
"Cost to Produce":4000,
"Grade":"H",
"Cost to Sell":25000,
"Strength":90
}
]
I am trying to use AJAX to read my JSON file.
$.ajax({
url: "dataProductJSON.json",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val) {
item.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
I am running my html from Eclipse with Apache Geronimo as the server.
Please Help.
You are missing a { in the below line
success: function (data)
Make it
success: function (data) {
Edit
You are having parsing the data incorrectly , do it as below
$.ajax({
url: "test.html",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val){
$.each(val, function (innerKey, innerValue){
item.push('<li id="' + innerKey + '">' + innerValue + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
You need to use 2 loop , one for the array and the other to loop through the object property
I tried things and it is working fine

jquery validation ie8 submitHandler not firing

I have this script:
var pUserName = $('#UserName'), pPassword = $('#Password'), pRememberMe = $('#RememberMe');
$(function () {
Initialize();
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
$('form#logon').valid();
});
});
function Initialize() {
returnUrl = getParameterByName('ReturnUrl');
$('form#logon').validate({
submitHandler: function (form) {
logOn(returnUrl);
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
};
function logOn(returnUrl) {
$.ajax({
url: '/_Account/LogOn',
type: 'POST',
data: '{ "UserName": "' + pUserName.val() + '", "Password": "' + pPassword.val() + '", "RememberMe": ' + pRememberMe.is(':checked') + ', "returnUrl": "' + returnUrl + '" }',
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function (o) {
if (o.success) {
// Success code
$.event.trigger('AjaxButtonSuccess');
} else {
showAnimatedStatusText($('.message'), o.error, 'error');
$.event.trigger('AjaxButtonError');
}
$.event.trigger('AjaxLoader');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
showAnimatedStatusText($('.message'), 'An uncaught error has occurred, please contact your system administrator (Error code: 150).', 'error');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
}
});
};
this works fine in all browsers except ie8. For some reason the submitHandler is never called. If I enter incorrect data invalidHandler is called fine, but submitHandler never is.
Does anyone know why?
Cheers,
/r3plica
The problem was that using a element in ie8 does not appear to work the same way as an even if you supply . To get this working I had to change my validation script to look like this:
$('#logon').validate({
submitHandler: function () {
// Do not submit
},
invalidHandler: function (e, validator) {
showAnimatedStatusText($('.message'), 'Please fill in the required fields highlighted below.', 'warning');
$.event.trigger('AjaxButtonError');
$.event.trigger('AjaxLoader');
},
errorPlacement: function (error, element) {
return true;
},
highlight: function (element) {
$(element).parent().addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).parent().removeClass("input-validation-error");
}
});
and the calling button click look like this:
$('#logon button').click(function () {
$.event.trigger('AjaxButtonClick', this);
$.event.trigger('AjaxLoader', '#logon .form');
if ($('#logon').valid()) {
logOn(returnUrl);
};
});
doing it this way fixed the issue.

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

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!

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