Set the value and display property for jquery's autocomplete source - jquery-ui

I've got a remote source which does not return id and value or label. How can I use it as a source for jquery's autocomplete plugin?

You should pass source a function that makes the AJAX request manually, and then performs some post-processing on the returned data:
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data) {
var processedData = $.map(data, function(item) {
return {
value: item._your_property, // Property you want to use for "value"
label: item._another_property // Property you want to use for "label"
}
});
response(processedData);
},
error: function() {
response([]);
}
});
}
Basically, use $.map to turn the array you get back into an array of objects that the autocomplete widget supports.
For a working example, check out the JSONP example on jQueryUI's demo page.

Related

select2 default value for single field

I'm using Jquery Select2 for my project. I want to keep a default value in a single input field when the page is loaded. I tried this by setting initSelection while I'm initiating the select2 component like this.
$(document).ready(function() {
allowClear: true,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
dataType: 'json',
url: "public/data.php",
data: function (term, page) {
return {
q: term, // search term
component: "map",
all_selected: $("#map-all").hasClass("active"),
parent_value: $("#city").val(),
child_value: ""
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON("public/data.php?q="+element.val()+"&component=map&all_selected=false&parent_value=&child_value=", null, function(data) {
if ($.isFunction(callback)) {
return callback(data);
}
});
},
formatSelection: format,
formatResult: format,
});
However this does not work as it is should be.
But, when I make multiple: true, as a select2 option, this works perfectly. How do I do this for single hidden field?
Thanks & Regards!
Okay, I solved this by changing the callback from return callback(data); to return callback(data[0]);. I think the reason behind this is since the field is not a multiple field, it only accepts a single object to the callback function.

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

jquery Select2 Ajax - How set value (initSelection)

How set in the drop-down list item selected by the user?
Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?
I have working script which retrieve data for the list.
$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
url: "index.php?modul=getusers",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return { results: data };
}
},
allowClear: true,
formatSelection: function(data) {
return data.text;
}
});
Standard data in ajax call:
{"text":"sample text", "id":"1"}
Input:
<input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid">
I tried to add the following code, but it doesn't work
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.php?modul=getusersfriend&q="+id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.
But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.
You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.
Which is what would happen here:
var id=$(element).val();
Here is a simple example of serializing your form.
PS: Don't really see what bootstrap has to do with anything.

Dynamically added link action produces 'This request has been blocked...' error

When I add category in controller action I return JSON object:
return Json(new { categoryName = category.Name, isPrimary = isPrim ? "1" : "-1", categoryId = categoryId }, JsonRequestBehavior.AllowGet);
In JS handler function I add item on page:
...
var totalLink = "<li style='color: #bbbbbb;'>" + result.categoryName + "<a class='removeCategoryButton' href='#lnk#'>remove</a></li>";
var lnk = '#Url.Action("RemoveCategoryFromLocation", "Location", new{locationId = Model.Location.TicketId, categoryId=-1})';
totalLink = totalLink.replace('#lnk#', lnk);
totalLink = totalLink.replace('-1', result.categoryId);
$('#otherCategories').append(totalLink);
...
When I click on remove link I call the following function:
$(function () {
$('.removeCategoryButton').click(function (event) {
event.preventDefault();
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
});
But I get the following error:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
This error happens only when I add item and want to remove it as soon after add on page. If I refresh page and click on remove link it works without problem.
Just to note when I get the error from above category is removed, so call works it just from some reason pop this error.
You seem to be adding the remove links dynamically and yet you have subscribed to the .click event handler only once when the DOM is ready. So make sure you do it in a lively manner. But since the .live() method is deprecated, depending on the jQuery version that you are using you should use either .delegate() or the .on() methods.
So with the latest version of jQuery it is recommended to use .on():
$(document).on(events, selector, data, handler);
$(document).on('click', '.removeCategoryButton', function () {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
Notice that you no longer need to wrap this in a document.ready callback.

Why ajax success is called once?

Why, if i write html method in javascript, it's called only once, but if i have only alert, it's calles every time, i change wy value in input (blur).
$(".quantity").blur(function() {
console.log("upd");
$.ajax({
url: "/line_items/update_quantity/"+$(this).attr("id"),
type: "GET",
data: {quantity: $(this).val()},
success: function(text)
{
alert(text);
$('.right').html(text);
},
error: function(){
alert('Ошибка javascript');
},
dataType : "html"
});
});
I need reload html partial after every blur...
Try doing this..
$(document).on('blur', '.quantity', function() {
// place your code here
});
I suspect you're replacing the dom element that the original blur binding is applied against. If you do that you remove the event handler. On() will keep it alive.
If .quantity is dynamic element (I think so) then try
$(document).delegate('.quantity', 'blur', function() {
// code
});
read here about delegate()

Resources