How to load data from database using autocomplete? - ajax

Here is my jQuery:
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response($data);
}
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());
here is my HTML,
<input type="text" id="user_role" name="user_role">
Here is my controller,
function search_username() {
$keyword=$this->input->get('term');
$this->load->model('chat_model');
$data=$this->chat_model->GetRow($keyword);
echo json_encode($data);
}
Here is my model
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
What I my trying to do is to load data form database using ajax but it's response is no properties but data is already there in table, please anyone help me for get rid of this.

First of all check this function it will return result or not
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
If it returning change the function
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
response($.map(data, function (value, key) {
return {
id:key,
label: value,
value: value
};
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());

Related

Kendo DataSource catch server response

In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}

Why i can not fetch data from controller from ajax function?

I'm beginner in asp.net mvc ,and want to fetch simple json from controller to ajax variable,for that purpose in view page write this ajax function:
<script>
var OutPut;
OutPut = "behzad";
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 2 },
success: function (color) {
OutPut= color;
},
error: function () {
alert('Error occured');
}
});
alert("I think is ok!"+":"+OutPut);
}
</script>
and this controller:
[HttpGet]
public JsonResult callService(int id)
{
string JSON = "behzad";
return Json(JSON,JsonRequestBehavior.AllowGet);
}
that ajax function call with this html code in view page:
<button type="button" class="btn btn-success" onclick="CallService()">Success</button>
but this line in ajax function:
alert("I think is ok!"+":"+OutPut);
Output is undefined,what happen?is controller return null?or why i get undefined alert?thanks.
Since the AJAX call is asynchronous, you should place the alert inside the success callback:
<script>
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
cache: false,
data: { 'id': 2 },
success: function (color) {
alert("I think is ok!" + ":" + color);
},
error: function () {
alert('Error occurred');
}
});
}
</script>

bootstrap typehead converting to ajax

I have a working sample with hardcoded data. I am trying to convert it to ajax call using bootstrap-typehead. I am not sure what I am doing wrong, but consol is shwoing error. Could some one help ? Thanks!
//Error
LOG: [object Object],[object Object],[object Object],[object Object]
SCRIPT438: Object doesn't support property or method 'toLowerCase'
JSFIDDLE
$('#selectAgent').typeahead({
source: function (query, process) {
return $.post('/eBus/EbusinessAgentServlet', { query: query }, function (data) {
console.log(data)
return process(data);
});
}
,
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});
It is working now.
var nameIdMap = {};
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query,
type: 'POST',
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
}
});
},
minLength: 2,
updater: function (item) {
console.log('selected id'+nameIdMap[item]);
return item;
}
});
});
function getOptionsFromJson(json) {
$.each(json, function (i, v) {
nameIdMap[v.fname] = v.agentID;
});
return $.map(json, function (n, i) {
return n.fname;
});
}
function getAjaxRequestData(query) {
return {
json: getJsonData(query),
delay: 1
};
// in the question this would be:
// return 'q='+query;
}
I think that because you're using ajax but javascript is has asyn (default) so you can try to using ajax this way to set async: false . Hpe this help.
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
url: "/eBus/EbusinessAgentServlet",
data: { query: query },
type: "POST",
async: false,
success: function (data) {
console.log(data)
return process(data);
}
});
},
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});

How to load a file using AJAX once and use its data multiple times?

I have this code where I load an XML file through AJAX:
$("#list").on("click", "li", function (event) {
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
alert("success");
},
error: function () {
alert("failure");
}
});
})
The issue is that I have a long list of clickable elements that use this code which is not very efficient. Is there a way to call AJAX function once and then use the data produced for other items on the list?
Just save the return value somewhere
$("#list").on("click", "li", function (event) {
var data = $("#list").data('test');
if (data){
//use data
}
else{
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
$("#list").data('test', data);
// use data
alert("success");
},
error: function () {
alert("failure");
}
});
}
})

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

Resources