Run jQuery code after AJAX jQuery load() - javascript

How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?

function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.

Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});

Related

google docs apps script function calling very slow

I'm writing a google docs apps script in making a google docs add-on. When the user clicks a button in the sidebar, an apps script function is called named executeSpellChecking. This apps script function makes a remote POST call after getting the document's text.
total time = time that takes from when user clicks the button, until the .withSuccessHandler(, that means until executeSpellChecking returns = 2000 ms
function time = time that takes for the executeSpellChecking call to complete from its start to its end = 1400 ms
t3 = time that takes for the remote POST call to be completed = 800ms
t4 = time that takes for the same remote POST call to complete in a VB.NET app = 200ms
Problems:
Why total time to complete is bigger than total function time by a staggering 600ms, what else happens there? shouldn't they be equal? How can I improve it?
Why t3 is bigger than t4 ? Shouldn't they be equal? Is there something wrong with POST requests when happening from .gs? How can I improve it ?
the code is (sidebar.html):
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
//var t1 = new Date().getTime();
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
//var t2 = new Date().getTime();
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//alert("total time to complete:" + (t2-t1) + "###" + go_TextAndTranslation.time);
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
and the called function code is (spellcheck.gs):
function executeSpellChecking(origin, dest, savePrefs) {
//var t1 = new Date().getTime();
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
//var t11 = new Date().getTime();
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
//var t22 = new Date().getTime();
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
//var t2 = new Date().getTime();
console.timeEnd("function time")
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}
Thank you in advance for any help.
EDIT: I updated the code to use console.time according to the suggestion, the results are:
total time: 2048.001953125 ms
Jun 21, 2021, 3:01:40 PM Debug POST time: 809ms
Jun 21, 2021, 3:01:41 PM Debug function time: 1408ms
So the problem is not how time is measured. function time is 1400ms, while the time it takes to return is 2000ms, a difference of 600ms and the POST time is a staggering 800ms, instead of 200ms it takes in VB.net to make the exact same POST call.
Use console.time() and console.timeEnd():
https://developers.google.com/apps-script/reference/base/console
I modified the code for you. console.timeEnd() outputs the time duration in the console automatically, so I removed the alert for you that showed the time difference.
You might want the strings that I used as the parameter as some sort of constant variable, so there are no magic strings used twice. I hope this is of use to you.
function runSpellChecking() {
gb_IsSpellcheckingRunning = true;
//gb_isAutoCorrecting = false;
gi_CorrectionCurrWordIndex = -1;
$("#btnStartCorr").attr("disabled", true);
$("#divMistakes").html("");
this.disabled = true;
//$('#error').remove();
var origin = $('input[name=origin]:checked').val();
var dest = $('input[name=dest]:checked').val();
var savePrefs = $('#save-prefs').is(':checked');
console.time("total time");
google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
if (gb_IsSpellCheckingEnabled) {
console.timeEnd("total time");
go_TextAndTranslation = JSON.parse(JSON.stringify(textAndTranslation));
var pagewords = textAndTranslation.pagewords;
var spellchecked = textAndTranslation.spellchecked;
//irrelevant code follows below...
}
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.executeSpellChecking(origin, dest, savePrefs);
}
function executeSpellChecking(origin, dest, savePrefs) {
console.time("function time");
var body = DocumentApp.getActiveDocument().getBody();
var alltext = body.getText();
var lastchar = alltext.slice(-1);
if (lastchar != " " && lastchar != "\n") {
body.editAsText().insertText(alltext.length, "\n");
alltext = body.getText();
}
var arr_alltext = alltext.split(/[\s\n]/);
var pagewords = new Object;
var pagewordsOrig = new Object;
var pagewordsOrigOffset = new Object;
var offset = 0;
var curWord = "";
var cnt = 0;
for (var i = 0; i < arr_alltext.length; i++) {
curWord = arr_alltext[i];
if (StringHasSimeioStiksis(curWord)) {
curWord = replaceSimeiaStiksis(curWord);
var arr3 = curWord.split(" ");
for (var k = 0; k < arr3.length; k++) {
curWord = arr3[k];
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length;
cnt++;
}
offset++;
} else {
pagewords["" + (cnt+1).toString()] = curWord.replace(/[`~##$%^&*()_|+\-="<>\{\}\[\]\\\/\n]/gi, '');
pagewordsOrig["" + (cnt+1).toString()] = curWord;
pagewordsOrigOffset["" + (cnt+1).toString()] = offset;
offset += curWord.length + 1;
cnt++;
}
}
var respTString = "";
var url = 'https://www.example.org/spellchecker.php';
var data = {
"Text" : JSON.stringify(pagewords),
"idOffset" : "0",
"lexID" : "8",
"userEmail" : "test#example.org"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
console.time("POST time");
var response = UrlFetchApp.fetch(url, options);
console.timeEnd("POST time");
var resp = response.getContentText();
respTString = resp;
var spellchecked = JSON.parse(respTString);
var style = {};
for (var k in pagewords){
if (pagewords.hasOwnProperty(k)) {
if (spellchecked.hasOwnProperty(k)) {
if (spellchecked[k].substr(0, 1) == "1") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#000000";
}
if (spellchecked[k].substr(0, 1) == "0") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#FF0000";
}
if (spellchecked[k].substr(0, 1) == "4") {
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";
}
if (pagewordsOrigOffset[k] < alltext.length) {
body.editAsText().setAttributes(pagewordsOrigOffset[k], pagewordsOrigOffset[k] + pagewordsOrig[k].length, style);
}
}
}
}
console.timeEnd("function time");
return {
"pagewords" : pagewords,
"pagewordsOrig" : pagewordsOrig,
"pagewordsOrigOffset" : pagewordsOrigOffset,
"spellchecked" : spellchecked
}
}

Correct Way To Re-Use HTML Blocks and Insert Dynamic Content With Javascript

I have a server that collects data from 10 sources and constantly pushes JSON data to a webpage. The page uses JSON.Parse to get it into an object widgetData. The object widgetData has 10 properties that I want to display in the "widget".
So, the server is pushing WidgetData1, WidgetData2, etc..
For each widgetData, I want to create/instantiate a new widget and show the data. If widget1 exists, then update the widget. Also, the widgets should be sorted by some text property(e.g. widgetdata.name).
Here's what I've done so far, but the it doesn't seem that robust:
<script type="text/javascript">
var properties = ["MachineID", "p1","p2,"p3","p4"];
var currentWidget;
function CreateBlock(widgetData)
{
var widgetID = widgetData.MachineID.replace(/ /g,"_");
var myWidget = document.getElementById('widget-' + widgetID);
if (myWidget == null)
{
CreateCard(widgetID);
}
var currentDate = new Date();
var day = currentDate.getDay();
var month = currentDate.getMonth(); //Be careful! January is 0 not 1
var year = currentDate.getFullYear();
var hour = currentDate.getHours();
var min = currentDate.getMinutes();
var sec = currentDate.getSeconds();
var dateString = year + "-" + ZeroPad(month+1,2) + "-" + day + " " + ZeroPad(hour,2) + ":" + ZeroPad(min,2) + ":" + ZeroPad(sec,2);
var data;
for (let i = 0; i < properties.length; i++)
{
data = widgetData[properties[i]];
AddDataElement(widgetID,properties[i],data);
}
AddDataElement(widgetID,"Timestamp",dateString);
}
//create the card
function CreateCard(cardID)
{
var parent
var newdiv
var cardElement = document.createElement("div");
cardElement.className = "card";
cardElement.id = "widget-" + cardID;
cardElement.style = "height:500px;";
parent=cardElement;
newdiv = document.createElement("div");
newdiv.className = "card-header";
parent.appendChild(newdiv);
//parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-body";
newdiv.id = "cardbody";
parent.appendChild(newdiv);
parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-title";
newdiv.id = "title";
newdiv.textContent = "title";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
newdiv.className = "card-sub-title";
newdiv.id = "subtitle";
newdiv.textContent = "subtitle";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
parent.appendChild(newdiv);
//last add to the parent div
var parent = document.getElementById("Cards");
parent.appendChild(cardElement);
}
//Add a data element
function AddDataElement(machineID, title, value)
{
var cardElement = document.getElementById("widget-" + machineID);
var cardElementBody = findChild("widget-" + machineID, "cardbody");
var dataElement = findChild2(cardElementBody, title);
if (dataElement == null)
{
dataElement = document.createElement("div");
dataElement.id = title;
dataElement.className = "card-item";
}
dataElement.innerText = title + ": " + value;
cardElementBody.appendChild(dataElement);
}
function CreateElement(parentDivObject, childName)
{
var dataElement = document.createElement('DIV');
dataElement.id = childName;
dataElement.textContent = childName;
parentDivObject.appendChild(dataElement);
}
function findChild(idOfElement, idOfChild)
{
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
function findChild2(parentElement, idOfChild)
{
//let element = document.getElementById(idOfElement);
return parentElement.querySelector('[id=' + idOfChild + ']');
}
function ZeroPad(num, places)
{
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
</script>
<script type="text/javascript">
var widgetList = new Set(); //hold list of widgets
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/');
//when data is comming from the server, this method is called
//ws.onmessage = function (evt) {
// inc.innerHTML += evt.data + '<br/>';
//};
ws.onmessage = function (evt)
{
var machineStatus = JSON.parse(evt.data);
if (!widgetList.has(machineStatus.MachineID))
{
widgetList.add(machineStatus.MachineID)
}
CreateBlock(machineStatus)
}
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
What is an alternative, proper way, or best practice to accomplish this?

Why does this give an Uncaught TypeError

var hatIds = [113333065] //This is the Ids
var PriceWanting = 15 //This is the price
var Loop = setInterval(function(){
for (var Id in hatIds) {
var hatLink = "http://m.roblox.com/items/" + hatIds[Id] + "/privatesales"
$.get(hatLink,function(data){
var Regex = /\<span class="currency-robux">([\d,]+)\<\/span\>/
var PriceSelling = data.match(Regex)[1]
PriceSelling = Number(PriceSelling.replace(",",""))
if (PriceSelling <= PriceWanting) {
var Regex2 = /<a href="\/Catalog\/VerifyTransfer\DuserAssetOptionId=([\d,]+)\Damp;expectedPrice=([\d,]+)">/
var HatBuyId = data.match(Regex2)[1]
var HatBuyLink = "http://m.roblox.com/Catalog/VerifyTransfer?userAssetOptionId=" + HatBuyId + "&expectedPrice=" + PriceSelling
var Explorer = document.createElement('iframe');
function Buy(){
Explorer.contentDocument.forms[0].submit();
};
Explorer.onload = Buy;
Explorer.width = "300";
Explorer.height = "400";
Explorer.src = HatBuyLink;
document.body.innerHTML = "";
document.body.appendChild(Explorer);
clearInterval(Loop)
}
});
}
console.log("!")
},0)
For some reason, I seem to be getting an Uncaught TypeError. I don't know why and would like some help in fixing it.

Codeigniter Auto completion is not working

Hello Auto completion is not working well in my application.When we type a name it displays only a blank list[ Screenshots attached ].
Controller Code
public function list_UserByName($letters)
{
if(strpos($letters, ","))
{
$letters1 = explode(",",$letters);
$lecount = count($letters1);
$letters = $letters1[$lecount-1];
}
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
$response=$this->user_model->getAutoUserList($letters);
}
Model Code
public function getAutoUserList($letters)
{
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//AND user_type='C' AND user_status='A'
$query="select * from gm_users where uname Like '%$letters%'";
$result_query =$this->db->query($query);
foreach($result_query->result() as $result)
{
//echo "###".$result."|";
//$pinlevel =$this->functions->get_pinlevel($result->pinLevel);
//echo $result->userId."###".$result->uname." [ ".$pinlevel." ] "."|";
echo $result->userId."###".$result->uname."".$result->address." ".$result->city."|";
}
}
billing.php
<input type="text" autocomplete="off" size="20" name="txtname" id="txtname" onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);" value=""/>
ajax-dynamic-list.js
/************************************************************************************************************
(C) www.dhtmlgoodies.com, April 2006
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var ajaxBox_offsetX = 25;
var ajaxBox_offsetY = 5;
var ajax_list_externalFile = site_url+'/catalog/list_UserByName'; // Path to external file
var minimumLettersBeforeLookup = 1; // Number of letters entered before a lookup is performed.
var ajax_list_objects = new Array();
var ajax_list_cachedLists = new Array();
var ajax_list_activeInput = false;
var ajax_list_activeItem;
var ajax_list_optionDivFirstItem = false;
var ajax_list_currentLetters = new Array();
var ajax_optionDiv = false;
var ajax_optionDiv_iframe = false;
var ajax_list_MSIE = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
var currentListIndex = 0;
function ajax_getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null){
returnValue += inputObj.offsetTop;
}
return returnValue;
}
function ajax_list_cancelEvent()
{
return false;
}
function ajax_getLeftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
// Edited
function ajax_option_setValue_bkp(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
val = ajax_list_activeInput.value.split(',');
vals = '';
count = val.length - 1;
for(i=0;i<count;i++)
{
vals = vals + val[i] + ',';
}
ajax_list_activeInput.value = vals + tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_option_setValue(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
ajax_list_activeInput.value = tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_options_hide()
{
if(ajax_optionDiv)ajax_optionDiv.style.display='none';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='none';
}
function ajax_options_rollOverActiveItem(item,fromKeyBoard)
{
if(ajax_list_activeItem)ajax_list_activeItem.className='optionDiv';
item.className='optionDivSelected';
ajax_list_activeItem = item;
if(fromKeyBoard){
if(ajax_list_activeItem.offsetTop>ajax_optionDiv.offsetHeight){
ajax_optionDiv.scrollTop = ajax_list_activeItem.offsetTop - ajax_optionDiv.offsetHeight + ajax_list_activeItem.offsetHeight + 2 ;
}
if(ajax_list_activeItem.offsetTop<ajax_optionDiv.scrollTop)
{
ajax_optionDiv.scrollTop = 0;
}
}
}
function ajax_option_list_buildList(letters,paramToExternalFile)
{
ajax_optionDiv.innerHTML = '';
ajax_list_activeItem = false;
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length<=1){
ajax_options_hide();
return;
}
ajax_list_optionDivFirstItem = false;
var optionsAdded = false;
for(var no=0;no<ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length;no++){
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].length==0)continue;
optionsAdded = true;
var div = document.createElement('DIV');
var items = ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].split(/###/gi);
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length==1 && ajax_list_activeInput.value == items[0]){
ajax_options_hide();
return;
}
div.innerHTML = items[items.length-1];
div.id = items[0];
div.className='optionDiv';
div.onmouseover = function(){ ajax_options_rollOverActiveItem(this,false) }
div.onclick = ajax_option_setValue;
if(!ajax_list_optionDivFirstItem)ajax_list_optionDivFirstItem = div;
ajax_optionDiv.appendChild(div);
}
if(optionsAdded){
ajax_optionDiv.style.display='block';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='';
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}
}
function ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,whichIndex)
{
if(whichIndex!=currentListIndex)return;
var letters = inputObj.value;
var content = ajax_list_objects[ajaxIndex].response;
var elements = content.split('|');
//alert(content);
ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()] = elements;
ajax_option_list_buildList(letters,paramToExternalFile);
}
function ajax_option_resize(inputObj)
{
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
}
function ajax_showOptions(inputObj,paramToExternalFile,e)
{
document.getElementById('saleUserId').value='';
if(e.keyCode==13 || e.keyCode==9)return;
if(ajax_list_currentLetters[inputObj.name]==inputObj.value)return;
if(!ajax_list_cachedLists[paramToExternalFile])ajax_list_cachedLists[paramToExternalFile] = new Array();
ajax_list_currentLetters[inputObj.name] = inputObj.value;
if(!ajax_optionDiv){
ajax_optionDiv = document.createElement('DIV');
ajax_optionDiv.id = 'ajax_listOfOptions';
document.body.appendChild(ajax_optionDiv);
if(ajax_list_MSIE){
ajax_optionDiv_iframe = document.createElement('IFRAME');
ajax_optionDiv_iframe.border='0';
ajax_optionDiv_iframe.style.width = ajax_optionDiv.clientWidth + 'px';
ajax_optionDiv_iframe.style.height = ajax_optionDiv.clientHeight + 'px';
ajax_optionDiv_iframe.id = 'ajax_listOfOptions_iframe';
document.body.appendChild(ajax_optionDiv_iframe);
}
var allInputs = document.getElementsByTagName('INPUT');
for(var no=0;no<allInputs.length;no++){
if(!allInputs[no].onkeyup)allInputs[no].onfocus = ajax_options_hide;
}
var allSelects = document.getElementsByTagName('SELECT');
for(var no=0;no<allSelects.length;no++){
allSelects[no].onfocus = ajax_options_hide;
}
var oldonkeydown=document.body.onkeydown;
if(typeof oldonkeydown!='function'){
document.body.onkeydown=ajax_option_keyNavigation;
}else{
document.body.onkeydown=function(){
oldonkeydown();
ajax_option_keyNavigation() ;}
}
var oldonresize=document.body.onresize;
if(typeof oldonresize!='function'){
document.body.onresize=function() {ajax_option_resize(inputObj); };
}else{
document.body.onresize=function(){oldonresize();
ajax_option_resize(inputObj) ;}
}
}
if(inputObj.value.length<minimumLettersBeforeLookup){
ajax_options_hide();
return;
}
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
ajax_list_activeInput = inputObj;
ajax_optionDiv.onselectstart = ajax_list_cancelEvent;
currentListIndex++;
if(ajax_list_cachedLists[paramToExternalFile][inputObj.value.toLowerCase()]){
ajax_option_list_buildList(inputObj.value,paramToExternalFile,currentListIndex);
}else{
var tmpIndex=currentListIndex/1;
ajax_optionDiv.innerHTML = '';
var ajaxIndex = ajax_list_objects.length;
ajax_list_objects[ajaxIndex] = new sack();
var search_key = inputObj.value.replace(" ","+");
//search_key1 = search_key.replace(",",",");
var url = ajax_list_externalFile + '/' +search_key;
ajax_list_objects[ajaxIndex].requestFile = url; // Specifying which file to get
ajax_list_objects[ajaxIndex].onCompletion = function(){ ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,tmpIndex); }; // Specify function that will be executed after file has been found
ajax_list_objects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words
return a.length;
}
function ajax_option_keyNavigation(e)
{
if(document.all)e = event;
if(!ajax_optionDiv)return;
if(ajax_optionDiv.style.display=='none')return;
if(e.keyCode==38){ // Up arrow
if(!ajax_list_activeItem)return;
if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
}
if(e.keyCode==40){ // Down arrow
if(!ajax_list_activeItem){
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}else{
if(!ajax_list_activeItem.nextSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
}
}
/*if(e.keyCode==13 || e.keyCode==9){ // Enter key or tab key
if(ajax_list_activeItem && ajax_list_activeItem.className=='optionDivSelected')ajax_option_setValue(false,ajax_list_activeItem);
if(e.keyCode==13)return false; else return true;
}
if(e.keyCode==27){ // Escape key
ajax_options_hide();
}*/
}
//document.documentElement.onclick = autoHideList;
function autoHideList(e)
{
if(document.all)e = event;
if (e.target) source = e.target;
else if (e.srcElement) source = e.srcElement;
if (source.nodeType == 3) // defeat Safari bug
source = source.parentNode;
if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea')ajax_options_hide();
}
Am a beginner in php as well as Codeigniter
Just echo your data in your controller
change
$response=$this->user_model->getAutoUserList($letters);
To
echo $this->user_model->getAutoUserList($letters);
change
onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);
to
onkeyup="ajax_showOptions(this,'list_UserByName',event);
there is a question on this topic on stackoverflow, but an entire different process.
My Codeigniter autocomplete with ajax

Global variable doesn't change with jquery function

I have a problem with my code. So I am trying to change the value of interval from 9 to the value of current_interval. This happens via a click event. But when the ChangePicture() function starts interval is still 9 (basically i have a picture rotator script that changes picture after 5 seconds).
var interval = 9;
var globalCounter = 0;
var temp = setInterval(function() {ChangePicture()}, 5000);
function SetInterval(i)
{
interval = i;
}
$(document).on("click", ".picture_button_lol", function(event){
var current_interval = $(this).children(".amount_of_pictures").val();
SetInterval(current_interval);
});
function ChangePicture()
{
var pictureId = globalCounter%interval;
ShowAndHide(pictureId);
globalCounter = globalCounter + 1;
}
function ShowAndHide(picId)
{
var picture = "bigview_" + picId;
var text = "bigview_text_" + picId;
var button = "bigview_button_" + picId;
var z_index = 1;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#ffffff";
document.write(interval);
for(var i=0; i<interval; i++)
{
if(i != picId)
{
picture = "bigview_" + i;
text = "bigview_text_" + i;
button = "bigview_button_" + i;
z_index = 0;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#000000";
}
}
globalCounter = picId;
}
You should trying using a callback :
function ChangePicture()
{
var pictureId = globalCounter%interval;
ShowAndHide(pictureId, function() {
globalCounter = globalCounter + 1;
});
}
function ShowAndHide(picId, callback)
{
var picture = "bigview_" + picId;
var text = "bigview_text_" + picId;
var button = "bigview_button_" + picId;
var z_index = 1;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#ffffff";
document.write(interval);
for(var i=0; i<interval; i++)
{
if(i != picId)
{
picture = "bigview_" + i;
text = "bigview_text_" + i;
button = "bigview_button_" + i;
z_index = 0;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#000000";
}
}
globalCounter = picId;
callback();
}

Categories