I added notifications to my web application.
This is the JavaScript that runs and shows the notifications on the notification bar.
With the notification, I want to show a notification icon for each line.
When I run the program, the image does not show.
This is how I tried to add the image:
$("#menu1").append('<li> <a> <span class=image><img src ="~/Theme/production/images/Annon.png"/> </span> <span>' + value.Ndetails + '</li><hr/>');
This is the full code:
function LoadData() {
$('#menu1').empty();
$('#menu1').append($('<li> Loading.. </li>'));
$.ajax({
type: 'GET',
url: $("#Get").val(),
dataType: 'json',
data: {},
success: function (data) {
if (data.Success == true)
$('#menu1').empty();
if (data.listNoti.length == 0) {
$('#menu1').append($('<li>There is nothing to show </li>'));
}
$("#notiCount").empty();
$("#notiCount").append(data.listNoti.length);
$.each(data.listNoti, function (index, value) {
$("#menu1").append('<li> <a> <span class=image><img src ="~/Theme/production/images/Annon.png"/> </span> <span>' + value.Ndetails + '</li><hr/>');
});
$("#menu1").append('<li><button onclick="ClearNotifications();"style="border:none;background-color: transparent;"><i class="fa fa-refresh"></i> Clear All Notifications</button></li>')
}
}
});
}
Looks like you provided bad relative path
<img src ="~/Theme/production/images/Annon.png"/>
Instead that, try this way
<img src ="./images/Annon.png"/>
First try to make an individual folder for your project
Then add all of your assets like images,audio,etc to that folder
Pictorial reference:
click this link to see an example for good relative path
Related
So I want to reload the div or web page only once for a Flask web app I am working on but as I don't know JS well I am stuck with a loop instead of it refreshing just once.
Why am I trying to do this?
Before getting to this page a user inputs data and it does calculations and then through Selenium, it does a website screenshot the process takes too long so when the user hits enter it does the calcs and then redirects to the new page once on that page I call a fx that submits in the background via ajax the selenium function, a gif is loaded instead of the screenshot.
The goal is that once the ajax route completes, the div or page reloads only once to replace the gif and shows the screenshot (which I did through if/else in Jinja) Hope that made sense if not let me know.
This is the div I want to work on
<div id="siteimg" class="c">
{% if a.imgofsite != "" %}
<img class="c" src="{{ url_for('static', filename = '' + a.imgofsite ) }}" style="overflow: hidden;">
{% else %}
<img class="c" src="{{ url_for('static', filename = 'img/load.gif') }}" style="overflow: hidden;">
<h5 class="c" style="overflow: hidden;">RENDERING SCREENSHOT</h5>
{% endif %}
Below is the JS I am using to submit the form and then call it.
<script type="text/javascript">
function img_load() {
$.ajax({
type: 'POST',
url: '/siteimage/{{ a._id }}',
});
}
</script>
<script>img_load();</script>
What I have tried:
This put me in a continuous loop
location.reload(true);
This gave me no response when I added it to the ajax call block
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
This one put me in a continuous loop as well
$("#siteimg").load(location.href + " #siteimg");
I guess you need to update the content of your div with the received data something like:
<script>
function img_load() {
$.ajax({
type: 'POST',
url: '/siteimage/{{ a._id }}',
success: function(response) {
$('#siteimg').append(response);
},
error: function(jqXHR, exception) {
console.log('Ajax status: ' + jqXHR.status + ', error: ' exeption);
}
});
}
</script>
So I figured it out. First, let me say thank you to all who were providing answers and editing to assist me in this issue.
For right now this is my solution. If any issues come up with this I definitely will add that info.
Once I am done with this project I definitely will be doing some JS/jQuery and Ajax courses.
<script>
var delayInMilliseconds = 60000; // 1 min
function img_load() {
$.ajax({
type: 'POST',
url: '/siteimage/{{ a._id }}',
},
setTimeout(function() {
$('#siteimg').load(document.URL + ' #siteimg');
}, delayInMilliseconds)
)
}
img_load()
</script>
Does this help?
SetTimeout is will recall the ajax specific to the div siteimg after 2 seconds.
setTimeout(function() {
$.get(window.location.href + " #siteimg", function(data) {
//empty old contents
$('#siteimg').empty().append($(data).find('#siteimg').children());
//recall after contents are emptied
$.ajax({
type: 'POST',
url: '/siteimage/{{ a._id }}'
});
$('#siteimg').append("<img src='https://www.w3schools.com/w3css/img_lights.jpg'>");
$('#siteimg').append(
"<img src='https://www.gettyimages.co.uk/gi-resources/images/CreativeLandingPage/HP_Sept_24_2018/CR3_GettyImages-159018836.jpg'>"
);
});
console.log($("#text").html());
}, 2000);
What if you use the browsers sessionStorage to track if the page was reloaded or not after the first visit.
At the end of your html insert the following js:
<script type="text/javascript">
if (!sessionStorage.getItem('reloaded')) {
// Page was not reloaded until last visit: do some stuff
sessionStorage.setItem('reloaded', true); // remeber the following reload for the next time
setTimeout(function () {
window.location.reload();
}, 100);
}else{
// Page was reloaded: clear your flag for the next visit
sessionStorage.removeItem('reloaded');
}
</script>
If you chose to show a modal that the user informs about the reload (what would good practise in my opinion) you should increase the setTimeout value from 100 to maybe 2500.
You can try it here (with addional console output): http://fiddle.bplaced.net/53414316/
Edit:
After reading your question again what you need is an ajax request. Reloading your site is just a workaround.
Although my solution should do what you have ask for - Andersons answer is what you should look for.
I have a jQuery up vote plugin. Everything is working fine except the error handling. My up vote plugin is in a foreach loop. like this below
if($RES['counter'] === '1'){
echo '
<td>
<div data-id='.$id.' class="upvote upvote-serverfault">
<a style="cursor:pointer;" class="upvote upvote-on" title="This idea is helpful"></a>
<span class="count">'.$counter.'</span>
<a class="downvote"></a>
<span id='.$index.'><span class="votingFeedback"></span>
</div>
</td>';
}
else
if($RES['counter'] === '-1'){
echo '
<td>
<div data-id='.$id.' class="upvote upvote-serverfault">
<a style="cursor:pointer;" class="upvote upvote-down" title="This idea is helpful"></a>
<span class="count">'.$counter.'</span>
<a class="downvote downvote-on"></a>
<span id='.$index.'><span class="votingFeedback"></span>
</div>
</td>';
}
The problem is when the user tries to span my voting system it will throw an error.The error checking is done in my PHP file and It's working but when I tries to dispaly the error on screen instead of showing the message on that particular topic is it shows on all the topic id
I was trying to make something like stack overflow. If you try to span the up or down vote it will throw and error but it's seems harder then I thought
My ajax call to my php file
<script>
var callback = function(data) {
$.ajax({
url: 'voting.php',
type: 'post',
data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred },
success: function(data) {
$(".votingFeedback").html(data);
}
});
};
$('.upvote').upvote({callback: callback});
</script>
When you get a response back from your ajax request you are selecting all voting feedback elements on the page because you are using a class selector. This is updating all the span with the class votingFeedback
You need to use a selector that is unique to the element you want to update. You already have a container div with the id. Use that as part of the selector.
$("[data-id='" + data.id + "'] .votingFeedback").html(data);
But you will also want to rename the parameter of the success function because you are defining data twice. This will mean that data.id doesn't exist anymore. Rename it to something like response or rename the parameter of the outer function.
You are getting unrecognized expression because you are replacing your original data variable with the new results from the ajax. from #allcutt answer try changing it to this.
var callback = function(data) {
$.ajax({
url: 'voting.php',
type: 'post',
data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred },
success: function(result) {
$("[data-id='" + data.id + "'] .votingFeedback").html(result);
}
});
};
$('.upvote').upvote({callback: callback});
I have been using the code from the top answer of the following post:
Need help understanding how to ajaxify a web site
It's working correctly when I try it with .html pages, as shown in the example. However, my pages are in php. Everything is working as it should with the php pages, except that when the url updates it shows as .html instead of .php.
In the code, taken from the answer I mentioned:
<script type="text/javascript">
var directory = 'content/'; //directory of the content we want to ajax in
var state = History.getState();
//for when they click on an ajax link
$('.ajaxify').on('click', function(e){
var $this = $(this);
var href = $this.attr('href'); // use the href value to determine what content to ajax in
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
e.preventDefault(); // we don't want the anchor tag to perform its native function
});
//for when they hit the back button
$(window).on('statechange', function(){
state = History.getState(); // find out what we previously ajaxed in
$.ajax({
url: directory + state.title + '.html', //create our path
dataType: 'html',
success: function(data) {
$('#content').html(data);
}
});
});
</script>
I have tried changing
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
to (changed .html to .php):
$.ajax({
url: directory + href + '.php', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.php'); // change the url and add our ajax request to our history
}
});
However, this has no effect. I have also tried changing the HTML:
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
to (adding .php to the hrefs):
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
but this stops the page loads from working completely. Any advice would be greatly appreciated. Thanks!
UPDATE: Sorry, I accidentally copied the data-dom-cache="true" line into my content-div. Seems very logical that the app is loading from the dom instead the new content! I've changed it to false and now it works perfectly.
Thanks.
I have a list which is dynamically generated. If someone is clicking on an entry in the list, the user is redirected to a new page where the data is loaded (dynamically). The data which is loaded depends on the list entry which the user has clicked.
When the app is loaded the first time, all things work well. But when the user is clicking on another list entry, the same data are represented as on the first run.
I've played around with the .empty() function from jQuery (to clear the div and append the new data) but it doesn't work.
EDIT:
My headlines.html file looks like this:
<div id="content>
<div id="headlineslist">
<ul data-role="listview" data-theme="c" id="headlineslist">
</ul>
</div>
</div>
<script>
$(document).ready(function() {
HeadlinesLoad();
});
</script>
Here's the Javascript file:
function HeadlinesLoad() {
$.ajax({
type: "POST",
url: "headlines_getter.php",
dataType: 'json',
cache: false,
success: function(data1) {
$.each(data1, function(i, currentObj) {
$('ul#headlineslist').append('<li data-role="list-divider"
class="ui-li ui-li-divider ui-bar-b">' + currentObj.main + '</li>').listview('refresh');
$.each(currentObj.sub, function (j, currentSub) {
$('ul#headlineslist').append('<li>
' + currentSub.name + '</li>').listview('refresh');
});
});
}
});
}
function headlineID(hID) {
window.localStorage.setItem("headlineID", hID);
}
function onHeadlinesLoad() {
var hID = window.localStorage.getItem("headlineID");
window.localStorage.removeItem("headlineID");
window.localStorage.clear();
$.ajax({
url: "headlinesclicked_getter.php?hID=" + hID,
success: function(html) {
if(html){
$("#headlineshome").empty();
$("#headlineshome").html(html);
}
}
});
}
And here is the snippet which lays in the HTML file where the data should be displayed (and refreshed on every new click the user does):
<div data-role="content" id="headlineshome"></div>
<script>
$(document).ready(function() {
onHeadlinesLoad();
});
</script>
I don't know why it doesn't work, so I ask you for help.
Thanks in advance.
Best regards, John.
Once you update your list using jQuery mobile, consider trigger "create" event, however that's out dated, so use
.page()
on your list like this:
$('ul#headlineslist').page();
i have this jQuery file, but the vote_up click handler keeps conflicting with the vote_down click handler, when i click the vote_down element it changes the vote_up element:
jQuery script:
$(document).ready(function () {
$("a.vote_up").click(function () {
//get the id
var the_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + the_id).html(msg).fadeIn();
$("#" + the_id + " img").attr("src", "img/uparrowActive.png");
}
});
});
});
$(document).ready(function () {
// the vote down function
$("a.vote_down").click(function () {
//get the id
var vote_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_down&id=" + vote_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + vote_id).html(msg).fadeIn();
$("#" + vote_id + " img").attr("src", "img/downarrowActive.png");
}
});
});
});
html:
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
the jQuery and ajax request is wokring fine, but the change of src is the problem, because when i click vote down, it changes the vote_up image!!
You can't use the same "id" value for two different elements.
If you're looking for some sort of strategy for focusing events to a repeating piece of data, utilizing IDs with the number appended to reference the various elements may work, but may not be the best approach.
I assume each repeating item has its own container that repeats. You may be better off placing a unique ID on that container, and finding the elements from there.
Take this for example:
<div id='outerContainer'>
<div id='set_123' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
<div id='set_124' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
<div id='set_125' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
</div>
You could use .delegate() to place click handlers on the #outerContainer that fire when you click the appropriate up/down elements.
Something like:
$(document).ready(function() {
$('#outerContainer').delegate('.vote_up', 'click', function() {
//get the id
var the_id = $(this).closest('.someContainer').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
// Make sure "this" in the callback refers to the element clicked
context: this,
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// Not sure where your vote_count is. See the HTML for my placement
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrowActive.png");
}
});
});
$('#outerContainer').delegate('.vote_down', 'click', function() {
//get the id
var the_id = $(this).closest('.someContainer').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
// Make sure "this" in the callback refers to the element clicked
context: this,
data: "action=vote_down&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// Not sure where your vote_count is. See the HTML for my placement
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/downarrowActive.png");
}
});
});
});
So the ID with the number you need is on each .someContainer. You traverse up to that container to get the ID, and do your .split().pop().
Then in the AJAX request, I set the context: property for $.ajax() so that this will still refer to the element that was clicked in your callback.
Inside the callback, you find the .siblings() that have the class .vote_count, and set its .html() content.
Finally you use .children() to get the img element, and set its src attribute.
This should give the general idea. You'll need to adjust for your HTML.