Having some problems getting JSTree to work with IE7 and 8. It works great on IE9, FF4 and Chrome.
It is loading data via the JSON_DATA plugin backed by an ASP.NET MVC3 controller action.
The problem is that the data is not getting loaded into the tree on IE7-8. I can verify the action is getting requested and no error is being thrown or at least caught in the error function.
$("#changeGroupTree")
.bind("select_node.jstree", function(event, data) {
// `data.rslt.obj` is the jquery extended node that was clicked
var id = data.rslt.obj.attr("id");
$("input[name='changeGroup_GroupId']").val(id)
.siblings("span")
.addClass("field-validation-valid")
.removeClass("field-validation-error");
$.ajax({
type: "GET",
url: "/api/group/gettree",
data: { groupId: id },
dataType: "JSON",
success: function(data, status, jqXHR) {
$("#changeGroup_SelectedGroup").html(data[0]);
},
error: function(jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
$().toastmessage("showErrorToast", data.ErrorMessage);
}
}); // end ajax
}) // end bind
.bind("loaded.jstree", function(event, data) {
})
.jstree({
core: {
animation: 200
},
plugins: ["themes", "json_data", "ui"],
themes: {
theme: "default",
dots: "true",
icons: "true"
},
ui: {
select_limit: 1
},
json_data: {
ajax: {
url: "/api/group/getgroups",
data: function(node) {
return { customerId: CUSTOMER_ID, parentId: (node.attr) ? node.attr("id") : "00000000-0000-0000-0000-000000000000" };
},
error: function(jqXHR, textStatus, errorThrown) {
alert("JSTree Error when getting Group data");
}
}
}
}); // end jstree
Here is the json that is returned from the server
[{"attr":{"id":"d9cc2cb9-fbc4-4726-a9b1-9eee00f1e2b8"},"data":"MTM","state":"closed","icon":"Group"}]
Am I missing something to get the data bound in the older IEs?
Thanks,
Turns out I had a self closing span tag in the html aka
<span class="field-validation-valid" />
Make this in to a well formed tag aka
And everything works perfectly.
Sigh, a whole day fighting this
Related
I can't get the item selected from the result set of jQuery UI Autocomplete to appear in the textbox after clicking on it, however i can navigate through them with keyboard and select with enter key. Here is my code:
$(document).ready(function () {
$('#t1').autocomplete({
source: function (request, response) {
// prepare url : for example '/api/artistapi?query=sonu
var autocompleteUrl = '/api/KeywordAutoComplete/' + request.term;
$.ajax({
url: autocompleteUrl,
type: 'GET',
cache: false,
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (data, id) {
return {
label: data.KeyText
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log('some error occured', textStatus, errorThrown);
}
});
},
minLength: 3,
select: function (event, ui) {
$('#autocomplete-textbox').val(ui.item.label);
return false;
}
});
I went trough some similar questions on Stackoverflow but none of them solved my issue. Some have suggested that the problem happens if in your header section you load more than one JQuery-UI Libraries. Here is my my header:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Eliminating any of these lines from my header did not help. Thank you all
I'm trying to pull data in my hybrid app through wordpress rest api. But I'm getting a blank screen. No error msg is thrown. Just a blank screen is coming. I have checked for syntactical error in lint and there's no error in code. I'm using the following code:
var BASE_URI = "https://public-api.wordpress.com/rest/v1.1/sites/smushbits.com/";
var POST_OFFSET = 0;
function load_post() {
$.ajax({
url: BASE_URI + "posts",
type: "GET",
dataType: "json",
data: {
"number": 10 ,
"offset": POST_OFFSET
},
error: function() {
alert("An error occured.");
},
success: function(response) {
$.each(response, function(index, data) {
$('<li><h1>'+data.posts[index].title+'</h1><p>'+getDays(data.posts[index].date)+'</p></li>').appendTo('#latest-list');
$(document).on("click", "#"+data.posts[index].ID, function() {
get_single_post(data.posts[index].title, data.posts[index].date, data.posts[index].URL, data.posts[index].content);
});
});
$('#latest-list').listview('refresh');
}
});
POST_OFFSET+=10;
}
$(document).ready(function(){
load_post();
});
Demo: http://smushbits.com/smushbits/www
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.
As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>
I am getting this error when I look at the javascript console
POST (url of website) GetUserPass 500 (Internal Server Error).
A popup also says that there is an unexpected token >
I am guessing that these two things are related so does anyone know anything about them or have they seen this before?
Here is the javascript code. The project is built in visual studio 2013.
<script type="text/javascript" src="../assets/plugins/data-tables/jquery.dataTables.datesorting.js"></script>
<script type="text/javascript">
var mvData = null;
var mvTable;
function GetDataSuccess(data, textStatus, XMLHttpRequest) {
$("#divMessage").html("").hide();
$("#userPassTable").show();
mvData = data.d;
mvTable.fnClearTable();
mvTable.fnAddData(data.d);
}
function GetDataError(XMLHttpRequest, textStatus, errorThrown) {
try {
var obj = jQuery.parseJSON(XMLHttpRequest.responseText);
$("#divMessage").html("An error occured: " + obj.Message + "<br>Exception Type: " + obj.ExceptionType).show();
}
catch (ex) { alert(ex.message); }
}
function logBodyOnLoad() {
$.ajax({
type: "POST",
url: "UserPass.aspx/GetUserPass",
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: GetDataSuccess,
error: GetDataError
});
mvTable = $('#userPassTable').dataTable(
{
"fnDrawCallback": function (oSettings) {
/* Need to redo the counters if filtered or sorted */
// if (oSettings.bSorted || oSettings.bFiltered) {
// for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++) {
// $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
// }
// }
},
"aoColumns":
[
{ "sTitle": "Vendor", sClass: "left_align" },
{ "sTitle": "Username", sClass: "left_align" },
{ "sTitle": "Password", sClass: "left_align" }
],
"iDisplayLength": 1000,
"aaData": [["", "", ""]],
bPaginate: false,
bFilter: true,
bSort: false,
bJQueryUI: true,
bAutoWidth: false
});
}
$(document).ready(logBodyOnLoad);
</script>
I am wondering if the "....aspx/GetUserPass" the slashed portion is causing this problem - sure it should not be a query string value?
This is a server-side error, which means you need to check your error logs on the server to see what is going on. If you don't have logging enabled (recommend ELMAH, very easy to plug in via NuGet) then two ways you can see what is going on:
1 - If you don't have additional data you are posting to the page, then the easiest is to just browse to the page by itself, localhost:xxx/UserPass.aspx/GetUserPass
2 - If you do have unique data you are posting and need to see the results with that specific data, then use Chrome - open the debugger tools (F12) take a look at the Network tab and it will show the request to the server, select it and click the "response" tab to see the detail it spits out. Should be the ASP.NET error HTML when you can parse through and hopefully help figure out what is going on.
Hope this helps get you further down the road!