pagination dropdown options in Ajax js - ajax

I have two select fields. States and cities. Displays a list of cities by state selection. But on Android phones, it appears very late(very slow). That's why I want to paginate.
how to pagination dropdown options in below my codes :
<script>
$('#stateCode').on('change',function(){
var stateID = $(this).val();
if(stateID){
$('.spinner').show();
$('#city').prop('disabled', 'disabled');
$.ajax({
type:"get",
dataType: 'json',
url:"{{url('cityjson/get-city-listz')}}?state_id="+stateID,
success:function(res){
$('.spinner').hide();
$('#city').prop('disabled', false);
if(res){
$("#city").empty();
$.each(res,function(key,value){
$("#city").append('<option value="'+value+'">'+key+'</option>');
});
}else{
$("#city").empty();
}
}
});
}else{
$("#city").empty();
}
});
</script>

Select2 comes with AJAX support built in, using jQuery's AJAX methods.
Include all the js and css plugins. Select2 4.0.0 or above needs to use.
In your HTML:
<select class="target" id="city"></select>
Note for below JS
items: contains the data that will be used and option
item object: each object contains {id:"1", test:"city 1"}
page: current page number
total_count: total number of cities for the state
term : this param can be used to search.
In your Javascript:
$("#city").select2({
ajax: {
url: "/cityjson/get-city-listz",
dataType: 'json',
data: function (params) {
return {
state_id:stateID,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
}
});

Related

How to use JSON result from autocomplete as variable for another autocomplete

I would like to ask You for help mi to figure it out, how to use result of first Complete which is giving me a client number as #select_client_id in another autocomplete.
At one page, i'm selecting order from autocomplete list:
$( function() {
$( "#select_order" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_order_out: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#select_order').val(ui.item.label); // display the selected text
$('#select_order_id').val(ui.item.value); // save selected id to input
$('#select_client_id').val(ui.item.client_id);
return false;
}
});
});
Then there is another input field which is selecting packages for this order, where i`m using a client id, from first autocomplete:
$("#select_package").autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_client_package_on_storage: request.term, client: client
},
success: function( data ) {
response( data );
console.log(client);
}
});
},
select: function (event, ui) {
$('.select_package').val(ui.item.label);
$('.select_package_id').val(ui.item.value);
return false;
}
});
For now, i've got only one client, so variable is declared by:
<script>
client="1";
</script>
How can i do it properly? :)
Well, it takes a little bit longer than normally, but it wasn't priory to figure it out :)
Answer is very simple :)
In #select_order autocomplete, i've add:
select: function (event, ui) {
$('#select_order').val(ui.item.label);
$('#select_order_id').val(ui.item.value);
$('#select_client_id').val(ui.item.client_id);
client_number=$("#select_client_id").val();
return false;
And at the end of body set a variable declaration:
<script>
let client_number = 0;
</script>
That solved my problem :)

Wordpress: Using AJAX to populate tinymce dropdown for use in a shortcode

To cut a long story short...
I am trying to dynamically populate a tinymce dropdown with a list of posts and the title to aid selection.
The various parts work, I can get my data with AJAX, I can make a dropdown using hardcoded text. How do I get the results of the AJAX call into the menu parameter in the tinymce.addButton method?
jQuery.ajax({
type: 'post',
url: ajaxurl,
data: {action : 'testimonial_list'},
success: function(data){
console.log(data);
// I now have the array to populate;
//{"Senior Advisor for Education Scotland":137,"Group HRD":117,"Utilities Director":118,"COO G4S":120,"MD Lexmark":60,"Human Resource Director, Connaught plc":55}
}
});
(function() {
tinymce.PluginManager.add('my_mce_button', function( editor, url ) {
editor.addButton( 'my_mce_button', {
text: 'Testimonials',
icon: false,
type: 'menubutton',
menu: [
// FOR EACH data KEY VALUE PAIR
{
text: //data ITEM KEY,
onclick: function() {
editor.insertContent('[my_shortcode id = //data VALUE]');
}
},
... // MORE ROWS
]
});
});
})();

jquery autocomplete is now working properly

I am working on jquery autocomplete in mvc platform. Now, my question is that in some textbox data autocomplete is working properly while in some textbox data autocomplete is not working properly.
For more clear, lets see the image of autocomplete task
now as per the image when I write the R word, I am getting the suggestion list of related R word.
now as per the second image I have written the whole word but still suggestion is not display.
Here is my code,
View
<input type="text" id="CustomerName" name="CustomerName" required data-provide="typeahead" class="typeahead search-query form-control autocomplete"
placeholder="Customer Name" />
<script>
$(document).ready(function () {
$.ajax({
url: "/ServiceJob/CustomerSerchAutoComplete",
method: "GET",
dataType: "json",
minLength: 2,
multiple: true,
success: function (data) {
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
//autocomplete(document.getElementById("CustomerName"), data.data);
$('#CustomerName').autocomplete({ source: data.data, minLength: 2, multiple: true });
}
});
});
</script>
Controller
[HttpGet]
public IActionResult CustomerSerchAutoComplete()
{
var customers = _Db.Ledger.Where(x => x.LedgerTypeId == (int)LedgerType.Customer).ToList();
var result = (from n in customers
select new
{
kk = n.Name.ToUpper()
}).ToList();
return Json(new { data = result });
}
As you are getting
Uncaught TypeError: Cannot read property 'substr' of undefined
For this error you should check that data is not null.
success: function (data) {
if(data != null)
{
autocomplete(document.getElementById("CustomerName"), data.data);
}
}

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Ajax - prevent click on a successful ajax request

I have a video thumbnail on my page, with a little icon "Thumbs Down". When you click on that, another thumbnail shows, replacing the other. User can do that as much as they want.
My code is now working only the first time. HTML:
AJAX:
$('.dislike_black').click(function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
When I click the icon the first time, its all fine, triggers the alert, the second time thought, no alert, and the browser is loading the href link.
I tried .preventDefault(); on the success and the complete event, but its not working.
Any hint on how to do this?
Your content is dynamically created so, depending on the version of jQuery you are using, you need the jQuery.live() or jQuery.on() method
jQuery.live() since jQuery 1.3 an event handler for all elements which match the current selector, now and in the future.
jQuery.on() since jQuery 1.7 - Attach an event handler function for one or more events to the selected elements.
Sample
jQuery.live()
$('.dislike_black').live("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
jQuery.on()
$('.dislike_black').on("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
More Information
jQuery.live()
jQuery.on()
Because you are replacing the dom which contains the anchor itself by new html in the ajax success handler. In this case you should use on which will attach event handler to parent or document element whatever you pass as the root element but will trigger the event only on the matching selector which you pass as the second argument. Try this.
$(document).on('click', '.dislike_black', function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
.on() reference: http://api.jquery.com/on/ (Ver. 1.7+)
If you are using older version of jQuery you can still achieve this using delegate method whose syntax is same as on but just the first 2 arguments are interchanged.
$(document).delegate('.dislike_black', 'click', function(e) {
//Your code here
});
.delegate() reference: http://api.jquery.com/delegate/
try
$(document).delegate('.dislike_black',"click",function(e) {
Try using event delegation.
// older jquery, use this line:
// $( ".dislike_black" ).live( "click", function ( e ) {
$( document ).on( "click", ".dislike_black", function ( e ) {
e.preventDefault();
alert( "test" );
var $aTag = $( this );
$.ajax( {
url : $aTag.attr( 'href' ),
type : "POST",
data : {
"sort" : $aTag.data( 'sort' ),
"page" : $aTag.data( 'page' )
},
success: function ( response ) {
$aTag.parents( "li" ).replaceWith( response );
}
});
});

Resources