problem ajax load with autocomplete.? - javascript

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});

I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Related

Retrieving of Data with different JSON formats

I am using jQuery and javascript in an ASP.NET Code
Below are the 2 functions that retrieve data in different formats
jQuery.ajax({
url: URL,
success: function (data) {
debugger;
try {
window["DataList"] = eval(data);
}
catch (e) {
window["DataList"] = [];
}
if (typeof (DataList) === "undefined" || !jQuery.isArray(DataList) || DataList.length === 0 || !DataList[0].id) {
jQuery("#" + divnomatch).text("No Matches Found.");
jQuery("#" + divnomatch).css("visibility", "visible");
jQuery("#" + divnomatch).css("display", "inline");
jQuery("#" + hdnid).val("");
jQuery("#" + hdnname).val("");
response([]);
}
else {
debugger;
jQuery("#" + divnomatch).css("visibility", "hidden");
jQuery("#" + divnomatch).css("display", "none");
fnShowHideObjTR("trResultsForRAUsers", false);
response(jQuery.map(DataList, function (item) {
return {
label: item.value,
value: item.value,
ID: item.id,
lNo: item.lNo,
eMail: item.eMail,
phyBUID: item.phyBUID
}
}));
}
}
});
For this, the data comes as below...
Below is the function that retrieves data in different format
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NoMatch':
jQuery("#" + divnomatch).text("No User's last name starts with '" + searchtext + "'.");
jQuery("#" + divnomatch).css("visibility", "visible");
jQuery("#" + divnomatch).css("display", "inline");
jQuery("#" + hdnid).val("");
jQuery("#" + hdnname).val("");
break;
case data.charAt(0) == "|":
lblErrorMessage.innerHTML = "Error occurred while retrieving the data: " + data.substring(1);
fnShowHideSpan("spanError", true);
break;
case data.charAt(0) == "<":
lblErrorMessage.innerHTML = "The server has not responded promptly to your \"Search as you Type\" queries. Please try again after a few minutes.";
fnShowHideObj("spanError", true);
break;
default:
debugger;
jQuery("#" + divnomatch).css("visibility", "hidden");
jQuery("#" + divnomatch).css("display", "none");
var rows = data.split("|");
var jsStr = "var DataList=[";
for (var i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace(/'/g, "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",value:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (DataList) != 'undefined') {
response(jQuery.map(DataList, function (item) {
return {
label: item.value,
value: item.value,
ID: item.id
}
}));
}
}
},
error: function (e) {
lblErrorMessage.innerHTML = "The server has not responded promptly to your \"Search as you Type\" queries. Please try again after a few minutes.";
fnShowHideObj("spanError", true);
}
});
Below is the data format in data variable
The second function works properly with the data and with its unique pipe seperator. How can I modify the code for first function which contains array of items to be pulled even with comma separator in the field in the front end as below...
So the problem that first function doesn't work at all or it formats the response to the incorrect format?
The suspicious thing I see now is the one of the conditions in the first if statement. !DataList[0].id would evaluate to true in case there is and object with ID equals to 0 which is incorrect logic I assume.

getJSON does not work on button click but does with hitting enter key

My getJSON request and the rest of my function works fine if the user hits enter after filling out the field however my function does not get past the getJSON request if they click the search button.
I've found some similar post on SO but haven't been able to fix my issue yet. I've tried adding .live before my .click event and also tried adding e.preventDefault in a couple different spots but that hasn't resolved it either.
My HTML looks like this
<input id="zipCode" maxlength="5" type="text"> <button id="zipSearch" onclick="findByZip()">Search</button></p>
My JS looks like this
$(document).ready(function () {
$('#zipSearch').click(findByZip);
$('#zipCode').bind('keydown', function (e) {
if (e.keyCode === 13) { // 13 is enter key
e.preventDefault();
findByZip();
return false;
}
});
}
);
function findByZip() {
console.log('running findByZip');
var zip = $('#zipCode').val();
var stateName = $('#stateName');
stateName.text("Reps for " + zip);
$("#results").empty();
var url='//something.com/api/Reps?Zipcode=' + zip;
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
if (data.length == 0) {
var header = "<h3>No matches found.</h3>"
$('#result').append(header);
}
else {
$.each(data, function (i, item) {
var header = "<h3>Manufacturer's Representative</h3>";
var businessName = $("<h4 id=businessName" + i + "></h4>").text(item.BusinessName);
var contactName = $("<h4 id=contactName" + i + "></h4>").text(item.Contact);
var address = $("<div id=address" + i + "></div>").text(item.Address);
var address2 = $("<div id=address2" + i + "></div>").text(item.City + ", " + item.State + " " + item.Zipcode);
var phone1 = $("<div id=phone1" + i + "></div>").text("PH: " + item.Phone1);
var phone2 = $("<div id=phone2" + i + "></div>").text("PH2: " + item.Phone2);
var fax = $("<div id=fax" + i + "></div>").text("FAX: " + item.Fax);
var email = '<div id=email' + i + '>' + item.Email + '</div>';
var website = '<div id=website' + i + '>' + item.Website + '</div>';
if (item.RegionalRepId == item.Id) {
header = "<h3>Regional Manager</h3>";
}
$("#results").append(header, businessName, contactName, address, address2, phone1, phone2, fax, email, website);
if (businessName[0].textContent == "null") {
$("#businessName" + i).remove();
}
if (contactName[0].textContent == "null") {
$("#contactName" + i).remove();
}
if (address[0].textContent == "null") {
$("#address" + i).remove();
$("#address" + i).remove();
}
if (phone1[0].textContent == "PH:null") {
$("#phone1" + i).remove();
}
if (phone2[0].textContent == "PH2:null") {
$("#phone2" + i).remove();
}
if (fax[0].textContent == "FAX:null") {
$("#fax" + i).remove();
}
if (email.includes("null")) {
$("#email" + i).remove();
}
if (website.includes("null")) {
$("#website" + i).remove();
}
});
}
});
}
expected result is to just pull and display data by different click events and searches to a map. Clicking on a state works, typing in a zipcode and hitting enter works, but typing in a zipcode and clicking search does not work.
If you guys have any suggestions it would be greatly appreciated. Young in my career, mostly have worked in .NET, C#, and Xamarin. Unfortunatly JS and JQuery are a little new to me. Thanks!
My form wasn't preventing a default on form via the submit button. It was only preventing the default on enter. Once I added type="button" inside my <button> tag everything worked fine.

Find and remove date in jQuery

I use RSS to get posts from my WordPress website and in its name have date in title and I want to remove the date from its title and use date from rss instead
The Result I want (image) I want to remove date on title (red cross) and use rss date(green underline) instead
The problem is date format in title is not international format
Any idea to make jQuery to detect this date formula and replace(remove) it?
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-langs.min.js"></script>
<script type="text/javascript" src="http://www.sd.ac.th/main/wp-content/rss_fetch/FeedEk.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divRss').FeedEk({
FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=121',
//FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=234',
MaxCount: 10,
ShowPubDate: true,
ShowDesc: false
});
/*setInterval(function(){
$('.itemTitle a').each(function() {
var text = $(this).text();
$(this).text(text
.replace('[', '')
.replace(']', '')
.replace('59', '')
.replace('60', '')
);
});}
, 1);*/
});
function reloadFunction() {
location.reload();
}
</script>
<button onclick="reloadFunction()">R</button>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="http://www.sd.ac.th/main/wp-content/rss_fetch/rss_style.css">
<div id="divRss"></div>
FeedEk.js (Plugin that I use for fetching my feed)
/*
* FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API
* http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk
* Author : Engin KIZIL http://www.enginkizil.com
*/
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
If it is always and the only thing between brackets ([ and ]) and it's always at the end of the string then use this:
text = text.replace(/(\[.*\])$/, replacementDateString);
Read about Regular Expression.

Getting values of inputs generated using jQuerys html() function

I have a page with a table and when I click edit I change the table elements into inputs using jQuerys html() function.
I then want to have the user edit the values of the inputs and save these to database, problem is when I try and grab the data I get undefined for all the inputs that are created with the html() function.
I am sure it is something to do with this.. Any help would be great! Here is my code:
$('[name="edit"]').click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $(this).attr('data-invoice-number'),
'count': $(this).attr('data-count')
};
var description_text = $('[data-description-' + data.count).text();
var rates_text = $('[data-rates-' + data.count).text();
var quantity_text = $('[data-quantity-' + data.count).text();
console.log(description_text);
$('[data-description-' + data.count + ']').html('<input type="text" name="description" value="' + description_text + '" />');
$('[data-rates-' + data.count + ']').html('<input type="text" name="rates" value="' + rates_text + '" />');
$('[data-quantity-' + data.count + ']').html('<input type="text" name="quantity" value="' + quantity_text + '" />');
$(this).css('display', 'none');
$('[name="save"][data-count=' + data.count + ']').css('display', 'inline-block');
$('[name="cancel"][data-count=' + data.count + ']').css('display', 'inline-block');
});
$('[name="save"]').unbind().bind().click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $('[name="save"]').attr('data-invoice-number'),
'description': $('[name="description"]').val(),
'rates': $('[name="rates"]').val(),
'quantity': $('[name="quantity"]').val(),
};
console.log(data); // this outputs undefined for values above generated using html() method
if (data.description == '') {
append_alert('danger', 'Please enter a <b>Description</b>');
} else if (data.rates == '') {
append_alert('danger', 'Please enter your <b>Rates</b>');
} else if (data.quantity == '') {
append_alert('danger', 'Please enter a <b>Quantity</b>');
} else {
$.post('edit_invoice_item', data, function() {}).done(function() {
append_alert('success', 'Item Edited!');
setTimeout(function() {
location.reload();
}, 2000)
});
}
});
Regards
For dynamically added elements use event delegation
Change
$('[name="edit"]').click(function(e) {
To
$(document).on('click', '[name="edit"]', function(e) {
AND
$('[name="save"]').unbind().bind().click(function(e) {
To
$(document).on('click', '[name="save"]', function(e) {

JQuery access some JSON data

I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.

Categories

Resources