I'm trying to do muti-values autocomplete.
http://jqueryui.com/autocomplete/#multiple
I am trying to make sense of the code but I cannot figure out the response part. (I am new to javascript. I'm doing a project in Grails which I started to learn just a month ago... I'm a total newbie...)
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter // Please explain this part for me
(availableTags, extractLast( request.term ) ) );
Please explain response( $.ui.autocomplete.filter part for me. Also if I want to use JSON source from my Grails controller, how can I replace availableTags?
Thanks in advance.
FWIK code you posted is part of initialization of widget.
While initializing you need to mention the source for the dropdown.
Source can be one of following:
1) Array
2) String
3) Function( Object request, Function response( Object data )
To answer response part: It is a function which takes care of filtering the result for widget.
To answer JSON source part:
If Source is JSON then you need to specify the host who will be serving that JSON. Whenever user types in on widget there will be call to host with request parameter named as TERM. So you need to make sure to filter it from request and return the JSON for that request.
Read more about it here:
View source for function in autocomplete with Array as input.
http://jqueryui.com/autocomplete/#multiple
View the Source definition and API docs:
http://api.jqueryui.com/autocomplete/#option-source
Response under event on API documentation is different than response mentioned in posted code above.
For ui.autocomplete.filter method refer to source code of the JS that is being imported that might give you better understanding of the code. But as per my understanding response function being called in above code under source is a callback to delegate back to autocomplete after extracting last term from array.
ui.autocomplete.filter method will filter the desired elements from list being provided and callback the same function to extract more. As I read it does pull one element out at a time. (refer to extract and split functions in under view source above)
Sorry for the big answer but read the documentations and other posts, article about it that would give better idea about the code.
Related
I am playing around with a OData service and I am very confused when to use this
var oModel = new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org/V3/(S(k42qhed3hw4zgjxfnhivnmes))/OData/OData.svc");
this.getView().setModel(oModel);
vs
var oModel = new sap.ui.model.odata.ODataModel("odatserviceurl", true);
var productsModel = new JSONModel();
oModel.read("/Products",
null,
null,
false,
function _OnSuccess(oData, response) {
var data = { "ProductCollection" : oData.results };
productsModel.setData(data);
},
function _OnError(error) {
console.log(error);
}
);
this.getView().setModel(productsModel);
I have two working example using both approach but I am not able to figure out why using read method if I can achieve same with first version. Please explain or guide me to the documentation which can clear my confusion.
Ok, lets start with the models:
JSON Model : The JSON model is a client-side model and, therefore, intended for small datasets, which are completely available on the client. The JSON model supports two-way binding. NOTE: no server side call is made on filtering, searching, refresh.
OData Model : The OData model is a server-side model: the dataset is only available on the server and the client only knows the currently visible rows and fields. This also means that sorting and filtering on the client is not possible. For this, the client has to send a request to the server. Meaning searching/filtering calls odata service again.
Now, lets look at scenarios where we will use these models:
Scenario 1: Showing data to user in a list/table/display form. Data manipulation is limited to searching and filtering. Here, I would use oData model directly to controls as only fetching of data is required.( your method 1) (NOTE: One way binding). Remember here all changes require a call to server.
Scenario 2: I have an application which has multiple inputs, user can edit changes, also some fields are calculated and mandatory. All in all, many user changes are done which may be temporary and user might not want to save them. Here, you dont want to send these temporary changes to backend as yet. You way want to manipulate, validate data before sending. Here, we will use JSON Model after reading data from odata model ( your method 2). Store the changes in local JSON model, validate and manipulate them and finally send the data using Odata create/update. Remember here all changes DO NOT require a call to server as data is present in local JSON MODEL.
Let me know if this helps you. :)
EDIT : Additional Information :
As per your comment :
Documentation says oModel.read' trigger get request but new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org/V3/(S(k42qhed3hw4zgjxfnhivnmes))/OData/OData.svc")` does the same thing so why and when to use oModel.read
Here, is where you misunderstood. The code
new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org/V3/(S(k42qhed3hw4zgjxfnhivnmes))/OData/OData.svc") will NOT send a read/get Request. It calls the odata services and fetches the metadata of the service. A service can have multiple entities.
For example: the service :http://services.odata.org/Northwind/Northwind.svc/ has mutiple entity sets such as Categories, Customers, Employees etc. So, when I declare : new sap.ui.model.odata.ODataModel("http://services.odata.org/Northwind/Northwind.svc/") it will fetch the metadata for service (not actual data). Only when you call the desired entity set, it will fetch the data. The Entity set is specified :
When you call the read method ( like you have specified '/Products')
Bind the entity set name directly to control like to List,Table etc ( items='{/Products}' )
There is few topics on the same subject, but non completely satisfied me!
I want to define the source of my autocomplete through a data attribute, like so:
<input data-behaviour='autocomplete' data-source='/path/to/source'>
I'm unable to get it programmatically through the source method:
$ ->
$('[data-behaviour~=autocomplete]').autocomplete
source: (req, resp) ->
return $(this).data('source')
Here is a non-working snippet to play with...
EDIT: a workaround I've found is to set it through the create method:
$ ->
$('[data-behaviour~=autocomplete]').autocomplete
create: (event, ui) ->
$(this).autocomplete( "option", "source", $(this).data('source') )
Check this snippet
But I don't really like this approach, I'm pretty sure better can be done
I'm not familiar with coffeescript; the jQuery UI automplete have a source option that allow you to make some custom stuff; in your case you can use the third option (function) using request and setting the response parameter.
Function: The third variation, a callback, provides the most
flexibility and can be used to connect any data source to
Autocomplete. The callback gets two arguments: A request object, with
a single term property, which refers to the value currently in the
text input. For example, if the user enters "new yo" in a city field,
the Autocomplete term will equal "new yo". A response callback, which
expects a single argument: the data to suggest to the user. This data
should be filtered based on the provided term, and can be in any of
the formats described above for simple local data. It's important when
providing a custom source callback to handle errors during the
request. You must always call the response callback even if you
encounter an error. This ensures that the widget always has the
correct state. When filtering data locally, you can make use of the
built-in $.ui.autocomplete.escapeRegex function. It'll take a single
string argument and escape all regex characters, making the result
safe to pass to new RegExp().
Ref: http://api.jqueryui.com/autocomplete/#option-source
Code:
$ ->
thisEl = $('[data-behaviour~=autocomplete]');
$('[data-behaviour~=autocomplete]').autocomplete
source: (req, resp) ->
resp(thisEl.data('source'));
Is only an example you have to implement the filtering pattern.
Demo: http://codepen.io/anon/pen/gjmHn
I ve a JS array, comprising multiple JS objects.
I want to convert JS array to JSON type, & pass that to controller (using AJAX - POST call).
So that I can retrieve the values from the Array of Objects, in my controller & save them in DB.
NB: I ve tried using $.stringify(myArry), but its not able to send data to controller in JSON format. Also I cant use $.toJSON(myArray), as I m not allowed to include a new plugin in our solution. :(
Plz suggest me any other idea.
Else if anyone can let me know how to deserelize the array in cotroller, that I ve sent by using $.stringify(myArry), that would also great.
Something like
var result = JavaScriptConvert.DeserializeObject(inputContent, JsonDataType);
Per this post, it looks like you'll have to add another plug-in:
JSON stringify missing from jQuery 1.4.1?
The Google solution looks good: http://code.google.com/p/jquery-json/
Or just use the JSON object from Crockford: https://github.com/douglascrockford/JSON-js
Ok, I am new at jQuery, but the JQGrid has peaked my interest. While implementing the grid, I have come across two problems that I am not sure how to solve. Both involve loading the grid with results.
How do you load the grid when you have parameters in your route. For instance, http://domain.com/search/results/2010/KY...I am wanting all results matching 2010 in Kentucky. In the javascript section of the grid initialization, I need to supply a URL (such as /search/gridResults/). How does one pass the other route values or at least use them to load the grid.
Same question, but more along the lines of when the page is loaded with posted form values from a search form.
Perhaps the URL is mostly to do with AJAX-y functions. It would be nice to sort and page with AJAX but to load the grid with AJAX is not neccessary.
Sorry for the long post, but I am sure others have faced this problem even though Google tells me otherwise :) PS - I have looked at Phil Haacks (sp?) and Craig something's blogs about using JQGrid, but neither touch upon loading pre-determined search results.
You can specify that directly with the 'url' key. e.g.: /search/gridResults/2010/KY
I actually use a custom javascript method in the postData jqgrid key for this (which you could use to solve your question 1 depending on the situation). This seemed kind of lame to me that I had to write this method, but I found something on the internet and had to keep hacking on it to make it flexible enough for my uses.
Code for custom method below. It reads params from the url directly. For POST params, you would need to do something else obviously, but to get them to jqgrid, it's the same idea:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash.length == 2) {
vars.push(hash[0]);
vars[hash[0]] = decodeURIComponent(hash[1].replace("+", "%20"));
}
}
return vars;
}
Hopefully that helps... If you come up with something better, I'd love to hear it. :)
I have a web page with lots of small images on it. In a typical scenario user clicks on image and expects it to change with a new image.
Requirements:
When user clicks on image, it should be immediately known to a controller in an Ajax way.
Some strings should be passed to a controller when user clicks on image.
Controller does its job and returns another image (which replaces old one).
Along with image controller returns a couple of extra strings (such as completion status).
Web page updates old image with new one and also updates other parts with these new strings.
Number of images on a page varies but potentially it can be a couple of dozens.
Question: What Ajax technique should be used here? I'm quite new to Ajax and don't feel solid with patterns. Should it be Json or something else?
Any code example would be very very welcome and helpful.
Thank you.
Well it sounds like you need a Event observer on the image object. On that image object, you could have various custom attributes, such as imageid="2", etc. With the element being observed onclick, you'd read the attributes of the elements and pass them on to an AJAX call. I'm not sure if the image is known by the database or would it be available on the page itself. Maybe a back/previous button? In either case, the AJAX call could either return JavaScript directly which then gets parsed to update the DOM and replaces the image with the new image source, or it could return a JSON response which then needs to get read and parsed by the AJAX callback and then updates the DOM. Easiest being to return JS code which gets parsed, but I prefer to have all my JavaScript in one file and not have it all over the place mixed with server side code.
It really depends on what AJAX library you are using.
With jQuery, you might do something like this.
$("#buttonImage").click(function () {
var imageid = $(this).attr('imageid');
$.getJSON("/controller/get_image/" + imageid,
function(data){
$("#buttonImage").attr("src", data.imagesrc);
});
});
And your /controller/get_image/123 would return a JSON response like...
{ 'imagesrc' : '/my/image.jpg' }
As far as I known, the only browser-safe way to change an image is by assigning a new URL to it's src attribute. If you return an image to a request that pass some parameters, it might prevent client-side cashing of the images. For these reasons, I would treat separately the transfer of textual data and images.
The completion status can always be return as the HTTP status text but if more information is needed from the server, you can always return it in JSON or XML, the simplest being JSON.
The responsiveness could be improved by preloading images on the mouseover event.