Javascript onload after ajax loading - javascript

After returning to main content by ajax load, function onload didn't run.
I can understand why, but how can I make it run in that condition?
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('chat').getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
$("#chat_main").load("chat", {
m: this.id,
ajax: 1 //here we are loading another page
});
}
}
}
</script>
<script>
function return_to_main() {
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
});
}
</script>
P.S. return_to_main() is binded on input type="button"

You are binding to the window.onload call. It does not magically get called every time the page content is updated. It is only called once. You need to call a function every time you want the code to run. So when the Ajax call is complete, you would been to trigger it.
BUT You are using jQuery so use it.
There is no reason why you would need to bind to every row on the table. Use event delegation. Now when the content changes, you will still have the events bound.
$( function () { //document ready
var chatMain = $("#chat_main");
chatMain.on("click", "table tbody tr", function () { //listen for clicks on table row
chatMain.load("chat",
{
m: this.id,
ajax: 1 //here we are loading another page
}
);
});
});

Call your function after the request:
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
}).done(onload); // <--
If .load does not produce a promise use:
$("#chat_main").load("chat", {
ajax: 1 //here we trying to load back main page
}, onload); // <--

Related

How do I use the .done() callback to run a function for new data being loaded on request?

I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>

JavaScript is not applying on page

I have below code that I have written in JavaScript and the script is referenced on the webpage. When the page loads, a call JavaScript happens and the logic's action should be rendered on the webpage.
Right now the script is firing on the webpage, but the action is not getting rendered on the webpage. However, if I execute the script on page console, changes happen.
<script>
function bannerLoad() {
var delayAddOn = setInterval(function() {
if ($(".add-ons").hasClass("current")) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$(".addons-container :last").append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
};
window.onload = function() {
bannerLoad();
};
window.onclick = function() {
bannerLoad();
};
</script>
Can anyone check if there is any issue?
You need to call the script when the page is fully loaded, else the function will be called and can't find the DOM elements.
You should wrap your code inside the ready function:
<script>
//OPEN THE READY FUNCTION
$(function(){
bannerLoad(); //Call of your function when the page is fully loaded
$(window).click(bannerLoad);
});
//CLOSE THE READY FUNCTION
function bannerLoad() {
var delayAddOn = setInterval(function()
{
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
</script>
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page , not just the DOM, is ready.
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
bannerLoad();
$(window).click(bannerLoad);
});
function bannerLoad() {
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
Your script has some little issues. I will try to evaluate them.
As bannerLoad is a function you don't need a ; at the end. Not an issue, just a hint.
As told before, bannerLoad is a function. So why would you wrap the function again in a function for your events? Just pass the function name directly, like window.click = bannerLoad;. Note that there are no bracers at the end, you just pass the name.
You function will always create a new delayAddOn variable with a new interval. So every time you click, another interval will be started and run in background. If you will do it like this, you need to put the variable on the outside of your function, to keep only one interval running at a time.
There is nothing wrong with using onload instead of a ready state from jQuery. But this belongs to you page setup and what you do. It would be more safe to rely on a ready state here, as told by others before. Because you already have a function, you could use it directly by $(bannerLoad);.
var delayAddOn;
function bannerLoad() {
delayAddOn = setInterval(function() {
if ($('.add-ons').hasClass('current')) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$('.addons-container :last').append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
}
$(bannerLoad);
window.onclick = bannerLoad;

Electron event fires multiple times

I have one page, that load new elements via jquery. I have page that have event listener like
ipcRenderer.send('getlist');
ipcRenderer.once('return:list', function (e, l, wn) {
console.log('a');
for(let i = 0; i < l.length; i++) {
$('.a').append('<div>'+l[i]+wn[i]'</div>');
}
$('.a').append('<div>End</div>');
});
Code that send data to page:
ipcMain.on('getlist', function (e) {
wn = [];
cfg['a'].forEach(s => {
wn.push(yaml.readSync('charcfg.yaml')['name']);
});
mainWindow.webContents.send('return:list', cfg['a'], wn);
});
And it's works perfectly until I load another page, and again load this page.
This event fires multiple times. Each time I come back to this page, more times it goes.
I tried to use
ipcRenderer.once('someevent', function(e, l){...});
It's works only ONE TIME. On third reload it's starts do listener multiple times again.
Code with this script loads with page!
Sorry for my english.Output
Function that loads page via jquery:
const htmlContent = $('.content');
function setContent(s) {
$('.content').animate({
opacity: 0
}, 200, function () {
setTimeout(function () {
htmlContent.load(s + '.html');
$('.content').animate({
opacity: 1
}, 200);
}, 100);
});
}
Actually there was TWO listeners that go twice.
It's ipcRenderer.on (replaced to .once) and jquery.on('click') that was bound to button that loads page. Fixed this with jquery.unbind().on('click').
Thanks for your help, obermillerk.

Resend AJAX request with link?

Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.

How to call a javascript function when cfgrid finish loading data

I am using Coldfusion 9 cfgrid. I want to do things:
1) Call a javascript function when all data inside cfgrid finish loading.
2) Call a javascript function when we click on next page in pagination.
1) use "onload" to specify a javascript function to call when the data has finished loading into the grid.
2) There is no parameter to specify a js function when data is reloaded, but you could get the id or the class of the 'next' button and bind your function to a click event on this element.
var ds = mygrid.getDataSource()
ds.addListener('load', function() {
http://www.coldfusionjedi.com/index.cfm/2009/4/9/Ask-a-Jedi-Noticing-an-empty-CFGRID
For your first question, you could do something like this
// function to fire when grid is finished loading
getTotalRows = function() {
var isGrid = ColdFusion.Grid.getGridObject('myGrid');
var isData = isGrid.getStore();
isData.addListener("load", function() {
if(isData.totalLength == 0) {
alert("No records found");
return false;
}
});
}
ColdFusion.Event.registerOnLoad(getTotalRows,null,false,true);
The last line (CF.Event etc) triggers the function call when the grid is loaded.

Categories

Resources