jQuery UI autocomplete no response bind or select is called - javascript

Jquery autocomplete for textbox search is not working ,webservice is called but the value is not binded to the textbox .please let me know what's wrong in this code.
.aspx page:
<asp:TextBox ID="tbStudentName" runat="server" class="tbStudentName" />
<asp:Button ID="btnStudentSearch" runat="server" meta:resourcekey="btnSearch" OnClick="btnStudentSearch_Clicked" />
Script:
function AutoCompleteName(target) {
var xhr;
$j("." + target.className).autocomplete({
source: function (request, response) {
if (xhr && xhr.readystate != 4) {
xhr.abort();
}
xhr = $j.ajax({
url: "../ServiceInterface/StudentLookupService.asmx/StudentSearch",
data: "{'pStudentId': '', 'pStudentName': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($j.map(data.d, function (item) {
return {
label: item.StudentId + ' : ' + item.LastName + ', ' + item.FirstName + ' ' + item.MiddleName,
value: item.FirstName + ' ' + item.LastName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
response([]);
}
});
},
select: function (event, ui)
{
$j("." + target.className).val = ui.item.firstName + ' ' + ui.item.lastName;
return true;
},
minLength: 1
});
}
Also when i enter two character in search box am getting error function,for 3 or more characters only the web service is called.
Please let me know your suggestions to make it work

Related

The Ajax request does not return an answer from the server

I have a code in JS like this:
$.ajax({
url: $("body").data("url") + "/Documents/CheckDoc",
data: {
docID: id
},
dataType: 'text',
}).success(function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '&copys=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
});
toastr.error("error");
It refers to the CheckDoc function on the server
And there it works great but when it comes back to JavaScript
It does not return to .success and does not reach the last row of the function: toastr.error
Which had to be carried out anyway
It is as if flying from this function and not returning to it again
Someone might know what the problem might be
Will help me a lot
Thank you
It's look like there is some mistake in your code, you closed your code after dataType: 'text', by }) , please try this and let us know:
$.ajax({
type: "POST",
url: $("body").data("url") + "/Documents/CheckDoc",
data: { docID: id },
contentType: "application/json; charset=utf-8",
dataType: 'text',
success: function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '&copys=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
},
failure: function (response) {
alert("failure");
},
error: function (xhr, ex) {
alert('error')
}
});

Jquery autocomplete - how modify returned data

I have code like this:
$(document).ready(function () {
if ($('#au').length <= 0) {
return;
}
var $project = $('#au');
$project.autocomplete({
minLength: 4,
source: function (request, response) {
$.ajax({
dataType: "json",
type: 'post',
cache: false,
data: {term: request.term},
url: '/Movies/ajax/',
success: function (data) {
if (isNaN($('#au').val())) {
response($.map(data, function (item) {
return {
label: item.Movies__name + " " + "(" + item.Movies__id + ")",
value: item.Movies__name
}
}));
} else {
response($.map(data, function (item) {
return {
label: item.Movies__id + " " + "(" + item.Movies__name + ")",
value: item.Movies__id
}
}));
}
}
});
},
select: function(event, ui) {
$("#au").val(ui.item.value);
$("#au").submit();
},
create: function (event, ui) {
},
open: function (event, ui) {
}
});
});
This code works fine. Basicly when You type in form "Alie", you will get
Alien(22)
Aliens2(32)
Aliens3(43)
Or when you type Id istead of movie name, you will get:
(22)Alien
(22)Other and so on....
So this code returns list of data - movie and id.
And now i want, to have first result without id, so when You type movie name like "Alie" you will get:
Alien
Alien(22)
Aliens(32)
First match without id.
Thanks for any replies.
response($.map(data, function (item, i) {
return {
label: item.Movies__name + (i != 0 ? " (" + item.Movies__id + ")" : ""),
value: item.Movies__name
}
}));
Use i for index in map function. If 0, you don't show id.

How to populate data in autocomplete textbox when a button is clicked?

I have a textbox with jquery autocomplete feature.It populates data based on a condition if '/' is entered and then a character.But i want to populate all the data in the autocomplete list when a button is clicked inspite of what ever data is there in the textbox.
My button :
<asp:Button ID="Button2" runat="server" Text="Button" />
And my autocomplete function with condition to populate data is:
<script type="text/javascript">
function pageLoad(sender, args) {
$(function () {
$("#<%=txtCu.ClientID %>").autocomplete({
source: function (request, response) {
if(request.term.indexOf("/") == (request.term.length-1) && enterFlag)
{
var term = request.term.slice(0,-1)
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
},
error: function (response) {
},
failure: function (response) {
}
});
};
},
select: function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); })
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<div><table><tr><td width='200px'>" + item.label + "</td>" + "<td width='110px'>" + item.val.split('~')[6] + "</td>" + "<td>" + item.val.split('~')[4] + "</td></tr></table></div>").appendTo(ul);
};
});
}
Do this to get the expected result
ASP Button, add class property CssClass
<asp:Button ID="Button2" runat="server" Text="Button" CssClass="btn"/>
and jQuery Part
$(document).on("click","btn",function(e){
e.preventDefault();
$("#<%=txtCu.ClientID %>").autocomplete("search", "");
$("#<%=txtCu.ClientID %>").autocomplete("select",function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
}
);
});
to close autocomplete on outside click
$(document).on('click', function(e){
var target = $(e.target);
if(target.attr("id") != "txtCu" && target.attr("class") != "btn")
{
$("#<%=txtCu.ClientID %>").autocomplete('close');
}
});
Note: You must set minLength: 0 in your autocomplete
Working DEMO
see this edit to your autocomplete code:
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
$('.ui-autocomplete').hide(); // <-- this line
},
edit XHTML :
<asp:Button ID="Button2" runat="server" Text="Button" Class="myBtn"/>
ps. it might be CssClass="myBtn" haven't used web forms in a bit
then jQuery:
$(function(){
$(document).on('click', '.myBtn', function(e){
e.preventDefault();
//maybe a prevent propigation line too just for other browsers like IE
$('.ui-autocomplete').show();
});
});
});

Using ng-repeat to show json data fetched from database

I have implemented a process to show my data from database in a #showdata div with the following method.
function UserCntrl($scope) {
getUser();
$scope.save = function () {
$.ajax({
type: "POST",
url: "UserService.asmx/InsertUser",
data: "{'Username':'" + $scope.Name + "','Email':'" + $scope.Mail + "','Password':'" + $scope.Password + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
$("#showdata").append("Username: " + $scope.Name + "<br />" + "Email:" + $scope.Mail + "<br />");
},
error: function (msg) {
alert(msg.d);
}
});
};
function getUser() {
$.ajax({
type: "POST",
url: "UserService.asmx/GetUserDetails",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#showdata").append("Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />");
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
};
}
Everything working just fine and all data showing properly in #showdata div. But now I want to do the same thing but by using the ng-repeat directive.
How can I achieve this?
as RGraham said, it's not the "angular way" to work with HTTP request but as a starting point, here's a working example:
js:
function EntryCtrl ($scope, $http) {
$scope.rootEntry = [];
$http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
$scope.rootEntry = root;
});
}
html:
<div ng-controller="EntryCtrl">
<ul>
<li ng-repeat="root in rootEntry">{{root.name}}</li>
</ul>
</div>
Live example: http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview
$scope.data = object
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
Assuming 'parsed' is in your controller's $scope property
<div id="showdata">
<div ng-repeat="(i, jsondata) in parsed" >{{"Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />"}}</div>
</div>

Ajax success function not waiting on internal script to complete before leaving scope

I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.

Categories