JQueryAutoComplete Not showing results - jquery-ui

I am trying to bind the text box and the JQuery AutoComplete feature. When I checked the Firebug AJAX Request & Response it returns like the following. But the textbox is not showing any items. Could you please advise me, what I am doing wrong? Thanks.
Here is my coding:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.FullDrugName,
id: item.DrugID
}
}))
}
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});

DataType property is representing the type of data that you're expecting back from the server.
you define data type as json but server returns you a xml output. You should change your DataType property to xml

In addition to #fealin's answer, you're going to need to change the way you process the xml response. It doesn't look like you have a d property on the return data, and you also need to look for the correct nodes in the XML structure and pull out their text to build the response array that you return to the widget.
Based on the XML you've provided, it might look something like this:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($(data).find("Drug").map(function (_, el) {
var $el = $(el);
return {
label: $el.find("FullDrugName").text(),
value: $el.find("DrugID").text()
};
}));
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
Here's an example that's just using the XML string (without an AJAX request): http://jsfiddle.net/J5rVP/29/

Related

Search2 - Ajax results with no search

I'm using ajax to pull in data from a php file (which returns json).
I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.
Code:
jQuery('.producttypesajax').select2({
allowClear: true,
placeholder: {
id: '',
text: 'Search by Product Type'
},
ajax: {
url: base + '/appProductTypeSearch.php',
dataType: 'json',
delay: 250,
data: function( params ) {
return {
q: params.term // search term
};
},
processResults: function( data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1
});
jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
});
https://select2.org/data-sources/ajax
I believe there's no native solution for this, but I managed to do it somehow.
Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".
Sample code:
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (jsonObject){
$('#mySelect').select2({ data: jsonObject });
}
});
It worked for me. Hope it helps.

jquery ajax always get error section when try to pass json object(simple)

var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.

synchronous ajax calls from jquery to mvc

I have to generate several graphs and each graph data I should get it from mvc controller.
so I am using the below jquery to do ajax calls from jquery to mvc
$(".emailgraphs").each(function () {
YAHOO.Report.Print("Email", $(this).attr("responsefield"), $(this).attr("id"), $(this).attr("metricid"));
});
Print: function (name, graphid, divid, metricid) {
try {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: m_oReport.ds,
data: JSON.stringify(m_oReport.printp(name, graphid, metricid)),
beforeSend: function () {
//Displays loading image before request send, till we get response.
//$("#" + divId).addClass("loading");
},
success: function (data) {
// if they define a success function (s), call it and return data to it.
if (typeof m_oReport.prints === "function") {
m_oReport.prints(data, divid, name)
}
},
error: function (err) {
$("#" + divid).html(err);
}
});
}
catch (err) { alert("catch"); }
}
The problem is the calls are asynchronous. sometimes I am getting one graph and sometime 2 like that and sometimes nothing.
Is there any fix for this?
try to use something like this
function getDataSync() {
return $.ajax({
type: "POST",
url: remote_url,
async: false,
}).responseText;
}

How to format response to jQuery AutoComplete

Im trying to use jQuery AutoComplete but all i get is a single item with all results all in it.
I have this ASP.Net WebMethod:
[WebMethod]
public static string FetchCompletionList(string term)
{
var json = JsonConvert.SerializeObject(CustomerProvider.FetchKeys(term, 8));
return json;
}
being called by this script:
$("[id$='txtLKey']").autocomplete({
minlength: 2,
source: function(request, response) {
$.ajax({
type: "POST",
url: "/Views/Crm/Json/Json.aspx/FetchCompletionList",
data: '{term: "' + $("[id$='txtLKey']") .val() + '", count: "8"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
alert(textStatus);
alert(errorThrown.toString());
}
});
}
});
And the result is this:
When what I actually want is a list of options the user can select i.e. each NZ should be an item in a list.
There are two problems here,
you need to pass data.d to response like response(data.d).
your value string is invalid it should be {"d":["NZ0008","NZ0015","NZ0017","NZ0018","NZ0026","NZ0027","NZ003??1","NZ0035"‌​]}

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

Resources