I have this JS code that is meant to display each dynamically loaded posts when clicked on:
function showPost(id) {
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
}); //get JSON Data for Stories
} //showPost
When I test the page 'http://howtodeployit.com/devotion/' on my mobile or windows browser, clicked on Daily Devotional Messages and I navigate between each posts, I notice the previously accessed post still shows for few seconds before the new post gets displayed.
How do refresh the page or DOM so it clears out previously accessed page.
Just empty() the contents of myPost while clicked on the item or on click of back button. Reason is that your previous content is still there in the mypost div, and your content page becomes visible even before the ajax call is executed which may take some time to complete say 700ms, so you will see the old content for that much period of time.
function showPost(id) {
var $myPost = $('#mypost').empty(); //emtpy it
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$myPost.html(output);
}); //get JSON Data for Stories
function start with a line $('#mypost').html(""); before going to another request to clear display content.
Also you can add a waiting message $('#mypost').html("Please wait..."); before showing content from next request.
function showPost(id) {
$('#mypost').html(""); //add this line
//$('#mypost').html("Please wait..."); //also you can add it to show waiting message.
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
}); //get JSON Data for Stories
}
You can empty() $mypost
var $myPost = $('#mypost').empty();
Related
I configured action cable, now I would like to use the following js function
$('.scroll-bar').scrollTop(row);
to scroll down the chat after submitting a message
So I tried to include the previous code in both app/assets/channels/messages.js and app/assets/javascripts/room.js.
The problem is until after I execute app/assets/channels/messages.js the html does not have then new <p></p> tag appended.
App.messages = App.cable.subscriptions.create('MessagesChannel', {
received: function(data) {
$("#messages").removeClass('hidden')
return $('#messages').append(this.renderMessage(data));
},
renderMessage: function(data) {
return "<p> <b>" + data.user + ": </b>" + data.message + "</p>";
}
});
This are my chat messages, I can not run .scrollTop(row) on a row that does not still exist.
I tested and the <p> tags are added after messages.js.
I found a temporary solution to solve this, by commenting return from return $('#messages').append(this.renderMessage(data)); and calling after the .scrollTop(row) method. The solution works, but this way only the html is appended to the page without <p> tags.. Somehow renderMessage is not working properly.
I am available for any info
Thanks a lot
Fabrizio Bertoglio
This is my temporary solution, not working correctly, because like this I will not append a <p> tag but just the text.
Basically like this the I am just appending the html without
"<p> <b>" + data.user + ": </b>" + data.message + "</p>"
You can see from the picture below that the message is not inside <p> tags.
This is what I have done, I commented the return to execute the .scrollTop() function after $('#messages').append(this.renderMessage(data));
app/assets/channels/messages.js
App.messages = App.cable.subscriptions.create('MessagesChannel', {
received: function(data) {
$("#messages").removeClass('hidden');
$('#messages').append(this.renderMessage(data));
height = $('.scroll-bar')[0].scrollHeight;
$('.scroll-bar').scrollTop(height);
/*return $('#messages').append(this.renderMessage(data));*/
},
renderMessage: function(data) {
return "<p> <b>" + data.user + ": </b>" + data.message + "</p>";
}
});
I think the solution is hear, from this post I followed to implement action cable, I don't understand who is directly calling the received: function(data) {}
is it the callback method subscribed inside messages_channel.rb?
class MessagesChannel < ApplicationCable::Channel
def subscribed
stream_from 'messages'
end
end
I don't have a clear idea how this callback method is calling the other method and how is the application flow.
Heroku Action Cable
Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?
In this function, the value parameter is being passed down to fill in my URL. This works perfectly.
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '(More from ' + value.snippet.channelTitle + ')</li>';
});
$('#results').html(html);
}
In this nearly identical function, the value param loses its value. I can't see how. It's difficult to debug why this is happening because console.log() just returns "ReferenceError: $ is not defined" no matter what I check (it returns this in the first section too, which works well).
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + ') </li>';
});
$('#results').html(html);
$('#results li a').click(function(){
playVid($(this).attr(value.id.videoId));
});
}
function playVid(vidID) {
var embedVid = 'https://www.youtube.com/embed/'+vidID+'?autoplay=1';
document.getElementById('player').src = embedVid;
}
Here I'm trying to push the value param (in the url again) to an iframe with id="player". The iframe receives an invalid param and the video won't play. Meanwhile the video plays in the first example. Where does value get lost?
value only exists within the scope of the each loop. So, first fix your reference error, and then I suggest the following changes in that second example:
1) Update the href with the videoId value in the each loop like in the first example:
<a href="https://www.youtube.com/watch?v=' + value.id.videoId + '">
2) And then launch the player with that value:
$('#results li a').click(function(e) {
e.preventDefault();
playVid($(this).attr('href'));
});
I have a default page with list of items. When I click on those Items I need to dynamically append data to div in Page B and redirect the app to Page B.
I added this div in PageB
''
On Click event I am doing following action in .js file:
'$(document).on('click', '#selectConcept', function (node) {
var ncid = this.textContent.slice(6,25);
$.ajax({
dataType: "json",
url: "http://txv-trmindexer01:8080/CommonTerminologyLeopardSearch/rest/getConceptByNcid/" + ncid,
error: function () {
alert("ERROR");
},
success: function (data) {
window.location.href = 'getfacets.html';
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
} });
});'
I am able to redirect page, but nothing is appended to Div.
Can anyone help me out with this..
I'm not really sure, but I guess the code runs before the new page is loaded. So you could try to wrap the code in a function run at onload event time
window.location.href = 'getfacets.html';
window.onload = function() {
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
}
The problem:
As soon as you set "window.location.href" property the page navigates to your page B and you loose your fetched data.
You have two solutions to the problem:
Use Single Page Application (SPA) application approach wherein you could create a new global scope for your fetched data, which can now be used by page B
Send the ncID as a querystring parameter to page B and and implement the service call and data appending logic on page B
I'm sure I've seen this before and know the answer to it but after 12 hours... my mind is complete mush.
I have a for loop in which I am trying to concatenate onto a string so that AFTER I can complete the string (thus completing a nice little table) that I had hoped to then insert into my html and show the user.
However, the things at the end of my function (after my for loop) are getting called before the for loop ever does....
function getEntries() {
$('#entryTotalsDiv').html('<img src="images/ajax-loader.gif" /> ... retrieving form totals.');
var entryTotalsTable = "<table id='entryTable' class='display' style='border:1px;'><thead><tr><th>Form Name</th><th>Hash</th><th>Entries</th></tr></thead>" +
"<tbody>"
//Get rows ONE at a time.
var countNumber = 1;
for (var frm = 0; frm < numberOfForms; frm++) {
$.post('ajax/getEntries.aspx',
{
'formNumber': frm
},
function (data) {
entryTotalsTable += "<tr><td>" + data[0].formName + "</td><td>" + data[0].formHash + "</td><td>" + data[0].formEntryCount + "</td></tr>";
//Now go and update the Form Retrieval div -- add 1 to the frm Number
$('#formNamesDiv').html(countNumber + ' of ' + numberOfForms + ' retrieved.');
countNumber++;
});
}
entryTotalsTable += "</tbody></table>";
$('#entriesDiv').html(entryTotalsTable);
//Now bind the table to the DataTables JQ script
$('#entryTable').dataTable();
$('#entryTable').show('slow');
}
If you notice, I wanted to close up the Table html at the end, but this gets called before my for loop is finished, thus screwing up my string...
?
entryTotalsTable += "</tbody></table>";
$('#entriesDiv').html(entryTotalsTable);
//Now bind the table to the DataTables JQ script
$('#entryTable').dataTable();
$('#entryTable').show('slow');
}
A solution could be to save every response in an array and test in every callback whether the current count is equal to the total count. Something like:
var countNumber = 1,
allData = [];
function runWhenFinished() {
if(countNumber === numberOfForms) {
var entryTotalsTable = "<table id='entryTable' class='display' style='border:1px;'><thead><tr><th>Form Name</th><th>Hash</th><th>Entries</th></tr></thead>" + "<tbody>";
for(var i = 0, l = allData.length; i < l; i++) {
entryTotalsTable += "<tr><td>" + allData[i].formName + "</td><td>" + allData[i].formHash + "</td><td>" + allData[i].formEntryCount + "</td></tr>";
}
entryTotalsTable += "</tbody></table>";
$('#entriesDiv').html(entryTotalsTable);
//Now bind the table to the DataTables JQ script
$('#entryTable').dataTable();
$('#entryTable').show('slow');
}
}
for(var frm = 0; frm < numberOfForms; frm++) {
(function(frm) {
$.post('ajax/getEntries.aspx',{'formNumber': frm}, function (data) {
allData[frm] = data[0];
countNumber++;
$('#formNamesDiv').html(countNumber + ' of ' + numberOfForms + ' retrieved.');
runWhenFinished();
});
}(frm));
}
I'm sure this can still be improved, but you get the idea.
If you really make 70 requests then you might want to rethink your strategy anyway. 70 simultaneous requests is a lot.
E.g. you could make one request and prove the minimum and maximum number of that should be retrieved / updated / whatever the method is doing.
$.post is asynchronous, meaning that it's firing off all the requests in the loop as fast as it can, and then exiting the loop. It doesn't wait for a response. When the response comes back, your row function is then called... but by then, all the posts have been sent on their way.
See the answers to this question here...
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
You'll need to change from $.post to $.ajax