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.
Related
I get the German text of a specific keyword (var title) and output it as html afterwards. This is working fine, but now I wanted to load the English text if the German text isn't available. This is also working fine with my code:
var length = 500;
var title = $('#title').attr('data-title');
var lang = 'de';
var url = 'https://' + lang + '.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
var text = val['extract'];
console.log('lang-' + lang + '-text: ' + text);
if (text) {
text = text.replace('Siehe auch:', '');
} else if (!text && lang != 'en') {
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
});
}
console.log('lang-end-text: ' + text);
if (text) {
text = text.length > length ? text.substring(0, length - 3) + '...' : text;
$('#text').html(text);
} else {
setTimeout(function () {
$('#text').html('<?= __('EMPTY'); ?>');
}, 1000);
}
console.log(data);
});
});
But after the second $.getJSON is closed, text is empty again. That means that
console.log('lang-en-text: ' + text);
is working and outputs the correct English text in the console, but after closing the $.getJSON the variable text has no value anymore, what I can confirm with the output in the console:
console.log('lang-end-text: ' + text);
How can I keep the value? Also is there a better way to check if the specific content I want to get (the text in this case) is available BEFORE, so I don't have to make two $.getJSON requests? Or is my way the right way to do it?
EDIT: It's working now!
I found the solution thanks to moopet and used .done and a new function called .setText to set the text. Maybe this helps others too as the question seems to get upvoted a lot. This is my code now:
var length = 500;
var title = $('#title').attr('data-title');
var lang = 'de';
var url = 'https://' + lang + '.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
var text = val['extract'];
console.log('lang-' + lang + '-text: ' + text);
if (text) {
text = text.replace('Siehe auch:', '');
} else if (!text && lang != 'en') {
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query' +
'&prop=extracts&exintro=&explaintext=&titles=' + title + '&redirects=0';
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: "select * from json where url=\"" + url + "\"",
format: "json"
},
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
}).done(function() {
setText(text);
});
}
console.log(data);
});
}).done(function() {
setText(text);
});
function setText(text) {
if (text) {
text = text.length > length ? text.substring(0, length - 3) + '...' : text;
$('#text').html(text);
} else {
$('#text').html('Text not available.');
}
}
You're running afoul of asynchronous javascript calls.
Your success callback:
function (data) {
$.each(data.query.results.json.query.pages, function (key, val) {
text = val['extract'];
console.log('lang-en-text: ' + text);
});
});
is called asynchronously. In other words, it's deferred until the HTTP request has finished.
Your
console.log('lang-end-text: ' + text);
is called immediately, before text is assigned, because that's how execution progresses. If you put the code for things you want to do with the text inside the callback function, you'll get the results you want.
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() {.
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
I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define the search type that they want and when a search is made, a URL is created which is something like #type/query/.
Currently, the search box is selected on page load with the $('#query').focus(); function however I want it to be deselected when the page is reloaded and there is text in #query. How can I go about doing this? I hope you can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
Remove $('#query').focus(); from where it is now, and add it in with an else like this:
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}else {
$('#query').focus();
}
I have inherited a website! which was designed to work in IE and only IE it seems.. I've now been asked to make the site run in Firefox. I've fixed most of the bugs without any problems but this one has me stumped.
setTimeout(fDelayedFunc, 1000);
This line of Javascript, works fine in IE but in Firefox the function fDelayedFunc never fires. I've removed the setTimeout and the function wrapper and tried running the code as part of the main function. This works without any problems at all.
There is alot of code involved but here's the main but I'm having trouble with. If you'd like to see anymore of the code please let me know.
setTimeout(fDelayedFunc, 0);
//Save the current text box value
var vCurrentTBValue = vJQElement.val();
function fDelayedFunc() {
if (vJQElement.val() == vCurrentTBValue) {
alert("test");
//Get position list box should appear in
var vTop = vJQElement.position().top + 25;
var vLeft = vJQElement.position().left;
//Had to put a special case in for account due to the position co-ords being wrong. This is due to a css error
if (vHiddenFieldToWriteTo == "#ctl00_ContentPlaceHolder1_hfAccountCode") {
vTop = vJQElement.position().top + 58;
vLeft = vJQElement.position().left + 200;
}
else {
vTop = vJQElement.position().top + 25;
vLeft = vJQElement.position().left;
}
//Create div element
var vDivElement = $("<div id='divSearchBox' style='position:absolute; top:" + vTop + ";left:" + vLeft + "; z-index: 40000;'></div>");
//Create list box
var vListBox = $("<select id='lbResults' tabIndex='" + vJQElement.attr("tabIndex") + "' size='4' style='height:400px;'></select>");
//Bind a function to the list box which will select the item via either tab or enter
vListBox.bind("keydown", function() {
//Check if tab or enter has been pressed
if (event.keyCode == 9 || event.keyCode == 13) {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Check if the up arrow has been pressed at the top of the listbox
else if (event.keyCode == 38 && $(vListBox.find(":selected")).val() == $(vListBox.find(":first")).val()) {
//Focus back on the search box
vElement.focus();
}
}).bind("dblclick", function() {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
});
//Get search field
var vSearchText = vJQElement.val();
var vDepotID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfDepotID").val();
var vCustomerID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCustomerID").val();
var vCountryID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCountryID").val();
var vConsignee = vJQElement.attr("boolConsignee");
//Set a loading image in place until call completed
vJQElement.css("backgroundImage", "url(images/small-loader.gif)");
vJQElement.css("backgroundRepeat", "no-repeat");
vJQElement.css("backgroundPosition", "right");
//Make AJAX call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewConsignment.asmx/fGetAddressesAndIDs",
data: "{'strSearchText' : '" + vSearchText + "', 'intDepotID' : '" + vDepotID + "', 'intCustomerID' : '" + vCustomerID + "', 'intCountryID' : '" + vCountryID + "', 'boolConsignee' : '" + vConsignee + "'}",
dataType: "json",
success: function fGetAddressesAndIDsResult(GetAddressesAndIDsResult) {
//Make sure there are results
if (GetAddressesAndIDsResult != null && GetAddressesAndIDsResult != "") {
var vNumberOfResults = 0;
var vNumberOfLearntAddresses = 0;
var vLearntAddressUniqueID = "";
//Try to get results (first call will work on Linux and catch will work on Windows)
try {
//Check array exists (if this fails will go to catch)
if (GetAddressesAndIDsResult.d.length > 0) {
//Loop through the results
$.each(GetAddressesAndIDsResult.d, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
}
catch (err) {
//Loop through the results
$.each(GetAddressesAndIDsResult, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
//Check if only 1 learnt address was found
if (vNumberOfLearntAddresses == 1) {
//Auto select this address
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val(vLearntAddressUniqueID);
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Add list box to div
vDivElement.append(vListBox);
//Check if any results exist in div
if (vNumberOfResults != 0) {
//Append div to page
$("body").append(vDivElement);
//Auto select first item
vListBox.find(".AddressOption:first").attr("selected", "true");
}
}
//Hide loading image
vJQElement.css("backgroundImage", "none");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//Inform user of error
alert("An error occured, please try again");
//Hide loading image
vJQElement.css("backgroundImage", "none");
}
});
}
}
Try this:
setTimeout(function() { fDelayedFunc(); }, 0);
I took setTimeout(function () {function1();}, 1500) out from the addEventListener("load", () => {code})
it worked for me inside Firefox
try this : setTimeout('fDelayedFunc()', 0);