jquery autocomplete not populating unless entered text is in the first result - javascript

Im having an issue with jquery autocomplete plugin. the textbox im using wont populate the results of autocomplete until i enter a value that is in the first entry of my data. After it populates that, then the autocomplete works how its supposed to.
$(document).ready(function () {
});
function textChange() {
var callback = function (request, response) {
var searchText = request.item;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
})
}
after playing around with it i got the following code to work, before i was using an onkeyup event in the text box but i guess i didnt need it. i dont know if this is efficient but it is working correctly now.
$(document).ready(function () {
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
});
});
var callback = function (request, response) {
var searchText = request.term;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}

You have to use a callback as the source option when you initialize the autocomplete (in your example you initialize the autocomplete every time a key is being pressed):
var callback = function(request, response) {
var searchText = request.item;
// Set searchField somehow here
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data)
{
var splitData = data.split(",");
response(splitData);
});
});
};
$( ".searchTextBox" ).autocomplete({
source: callback,
autoFill: true
});
There are some more examples and a more detailed description in the documentation.

Related

Ajax change variable automatically

I got an issue here. I found out that the global variable got changed every time it got into ajax.
$(document).on("keyup input", ".product-id", function () {
var id_prod = this.id.replace('prod_id_', '');
console.log('id_prod (outside ajax): ', id_prod);
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({
"display": "block"
});
if (inputVal.length) {
$.ajax({
type: 'POST',
data: { term: inputVal },
url: 'backend-search-inv.php',
success: function (data) {
resultDropdown.html(data);
$(document).on("click", "#result2 p", function () {
var inv_id = $(this).text();
//console.log('inv_id: ',inv_id);
$.ajax({
type: 'POST',
data: {
term: inv_id
},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ', id_prod);
},
error: function () {
console.log('Unable to access database.');
}
});
}); //end of result being clicked
}
});
}
else {
resultDropdown.empty();
}
});
I don't get it why the variable id_prod gets incremented everytime when it goes into ajax. Here is the screenshot of the console.log.
Referring to the screenshot, everytime I want to enter something to the id_prod = 2, the ajax always ended up updating the id_prod = 1, and then id_prod = 2 again automatically, and result in duplication of my data.
Can someone help me on this?
So basically I just declare the id_prod as a global variable and assigned 0 as it's default value. Then, for id_prod is basically assigned to new value once it's in the keyup input event.
Thanks to Mohamed Yousef for his answer in my own question's comment section!
//DECLARE id_prod as a global variable...
var id_prod = 0;
$(document).on("keyup input", ".product-id", function(){
id_prod = this.id.replace('prod_id_', '');
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({"display":"block"});
if(inputVal.length){
$.ajax({
type: 'POST',
data: {term:inputVal},
url: 'backend-search-inv.php',
success: function(data){
resultDropdown.html(data);
}
});
}
else{
resultDropdown.empty();
}
});
// WHEN RESULT BEING CLICKED...
$(document).on("click", "#result2 p", function(){
var inv_id = $(this).text();
$.ajax({
type: 'POST',
data: {term:inv_id},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ',id_prod);
$('#prod_id_'+id_prod).val(inv_info[0]);
$('#prod_qty_'+id_prod).val(1);
$('#prod_disct_'+id_prod).val(0);
$('#prod_type_'+id_prod).val(inv_info[1]);
$('#prod_colour_'+id_prod).val(inv_info[2]);
$('#prod_price_'+id_prod).val(inv_info[3]);
$('#result2').empty();
sumPrice();
},
error: function(){
console.log('Unable to access database.');
}
});});

Get the value of input tag for Ajax Request

<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/

How can I pass the value and corresponding name of a checkbox when checked using javascript in ASP.NET?

I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:
You can try the following code:
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());

How to pass extra parameter in jquery post request from outside click event?

Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});

Can't set HTML using jQuery

For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});

Categories