Reputation: 1681
$("#search_customer").autocomplete({
source: function (request, response) {
$.ajax({
url: "<?php echo base_url(); ?>" + "sales/get_customers",
type: 'GET',
data:request,
success: function (data) {
var object = JSON.parse(data);
if(object.length!=0){
$("#add_customer_div").hide();
response($.map(object, function (el) {
return {
label: el.phone,
value: el.name,
id: el.CustomerID
};
}));
}else{
// $("#add_customer_div").show();
}
}
});
},
select: function (event, ui) {
this.value = ui.item.label;
$(".ui-menu-item").hide();
event.preventDefault();
}
});
Above code is working fine but didn't limit data, it contains thousands of rows , but I want to limit it to 10 or 20 max. i am trying but failed to do it.
Upvotes: 0
Views: 49
Reputation: 33933
To send a "limit" along the ajax request:
var limit = 20; // the amount you wish.
$.ajax({
url: "<?php echo base_url(); ?>" + "sales/get_customers" + "?n="+limit,
//...
Then in your PHP ressource:
<?php
$default_n = 10; // a default value in case of omission.
if(isset($_GET['n'])){
$n = $_GET['n'];
}else{
$n = $default_n;
}
// Use this $n in the SQL statement.
// Example:
$sql = "SELECT * FROM table WHERE somecolumn='SomeValue' limit $n";
// ...
Note that you should NOT use the $n
variable exactly as this example.
You should use mysqli or PDO parametrized query... To avoid SQL injection.
But that is quite out of your question scope.
Upvotes: 0
Reputation: 8597
You could .slice
your object, to only contain 10-20 items, below is your success callback with a simple slice applied on the object, rest of the code is as you written. This does not utilize a loop like above.
success: function(data) {
var object = JSON.parse(data);
if (object.length != 0) {
$("#add_customer_div").hide();
object = object.slice(0, 10)
response($.map(object, function(el) {
return {
label: el.phone,
value: el.name,
id: el.CustomerID
};
}));
} else {
// $("#add_customer_div").show();
}
}
If you could however (If you have control over the server) more efficient would be to make an endpoint which only returns 10-20 items, this would save you transferring all this data you're not using.
Upvotes: 1
Reputation: 456
If you cant limit the result sent by api you can use a for loop instead of map like this
var result=[];
if(object.length!=0){
for(i=0;i<limit;i++){
result.push(object[i])
}
}
$("#add_customer_div").hide();
response($.map(result, function (el) {
return {
label: el.phone,
value: el.name,
id: el.CustomerID
};
}));
Upvotes: 0