bootstrap typehead converting to ajax - 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);
}
});

Related

if else condition in ajax not returning boolean

I'm using ajax and successfully getting the response. I'm unable to understand, why if-else condition is not returning boolean value as expected. Not sure, if I'm using the return in right place or not. Need help.
validateEverPresentRowWidgetValue: function (datafield, value, rowValues) {
if ((!value)) {
$.alert({
content: 'Please select Date!',
btnClass: 'btn-warning',
boxWidth: '30%',
title: 'Missed something!',
type: 'orange',
typeAnimated: true,
useBootstrap: false
});
return false; //Works fine
} else if (value) {
$.ajax({
url: 'checkForLeave.php',
dataType: 'json',
method: 'post',
data: {date: value},
success: function (response) {
if (response.length > 0) {
$.confirm({
title: 'Confirm!',
content: 'This date is NOT allowed! <br> Reason:' + response[0].comments,
boxWidth: '30%',
typeAnimated: true,
useBootstrap: false,
btnClass: 'btn-warning',
type: 'orange',
buttons: {
confirm: function () {
return true; //Problem in return
},
cancel: function () {
return false; //Problem in return
}
}
});
} else {
return true;
}
},
error: function (response) {
return false;
}
});
}
}

How to load data from database using autocomplete?

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
},
});
}());

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");
}
});
}
})

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

Resources