Refreshing div or page once with JS or jQuery / Ajax - javascript

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.

Related

Ajax Requests Slow in Django

I have the following ajax request in my django template:
$('#subjects').on('change', function() {
var subject = $('#subjects').find(":selected").text();
$.ajax({
type: "GET",
url: "/classes/" + term + "/" + subject , // or just url: "/my-url/path/"
dataType: "html",
success: function(data) {
$('#classes').html(data);
}
});
//remove courses
//remove overview
//get courses for specified subject
//put them under course
});
The "subject" id is for a select form like this:
<select size="7" class="form-control" id="subjects">
{% for subject in subjects %}
<option>{{ subject }}</option>
{% endfor %}
</select>
So, when a subject is changed, I send an ajax request to the server so that I can get the classes for that subject from the database (as there are thousands of classes). However, this takes ~1 second. If a user simply arrows down my list of subjects, then tens of ajax requests will be fired off in a second, causing a backup and slowing down the data being displayed properly.
I tried aborting all previous ajax requests before sending another one, but the problem is the server will still process these, so it did not fix the problem.
Is there any way to speed this up, and somehow only take 1 second any time a user scrolls down to a subject? Or, is there another method that anyone would recommend?
Follow up question. Another way I just thought of would be to only send the ajax request if an option is selected for longer than 1 second. this would make it take 2 seconds which is fine. Is there a way to do this?
Answering to your follow up question, here is a jQuery function that allow to delay the callback of an event a given amount of milliseconds:
(function ($) {
$.fn.delayOnEvent = function(onevent, callback, ms){
$(this).on(onevent, function( event ){
var srcEl = event.currentTarget;
if( srcEl.delayTimer )
clearTimeout ( srcEl.delayTimer );
srcEl.delayTimer = setTimeout(function(){ callback( $(srcEl) ); }, ms);
});
return $(this);
};
})(jQuery);
You can call it this way in your case:
$('#subjects').delayOnEvent('change', function() {
...
}, 1000); // one second delay
Do something like this enable/disable
$('#subjects').on('change', function() {
var subject = $('#subjects').find(":selected").text();
document.getElementById('subjects').disabled=true
$.ajax({
type: "GET",
url: "/classes/" + term + "/" + subject , // or just url: "/my-url/path/"
dataType: "html",
success: function(data) {
$('#classes').html(data);
document.getElementById('subjects').disabled=false
}
});
#rest of code

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

How to refresh a DIV in jquery (mobile)?

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();

Image and text does not change in a single click on completion of Ajax call without an alert statement

I have made a script where I update a field value via AJAX and then I change the related text and image on the page without reload. There are multiple such links and the html for one of them is
<li>
{% if object.attr1== 0 %}
<IMG SRC="{{ STATIC_URL }}images/unchecked.jpeg">
{% else %}
<IMG SRC="{{ STATIC_URL }}images/check.jpeg">
{% endif %}
<span style="padding-left:5px"><a id="update" title="Click to update status" href="/update/{{object.id}}/1/">Attribute Name</a>: </span>
<span id="sent_text">
{% if object.attr1 == 0 %}
Completed
{% else %}
Incomplete
{% endif %}
</span>
</li>
I basically send an AJAX link to the href of a tag. Since this is in li there are multiple such update links for different attributes of the object. My javascript is
$(function() {
$("a#update").click(function(){
var curr_elem = $(this) ;
var link = $(this).attr("href");
$.ajax({
type: "POST",
url: link,
success: function()
{
var text = curr_elem.parent().parent().find('span#sent_text').text();
if (text == 'Completed')
{
curr_elem.parent().parent().find('span#sent_text').html('In complete');
curr_elem.parent().parent().find('IMG').attr("src", "/static/images/check.jpeg");
}
else
{
curr_elem.parent().parent().find('span#sent_text').html('Completed');
curr_elem.parent().parent().find('IMG').attr("src", "/static/images/unchecked.jpeg");
}
alert(text);
},
error: function(xhr, status, error)
{
alert("Function failed!");
}
});
return false;
});
});
My problem is that the AJAX call is working correctly, the object status is being updated, but the image and text does not change in a single click if I remove the alert call. If the alert call is there then the image and text change there itself.
However If I remove it then, the change takes place when I click it twice. Can anybody please tell me why am I experiencing this strange behaviour.
Update: I know this will sound weird, but it is the case. My script is sometimes working and sometimes now. And by not working I mean that AJAX call is always successful but sometimes the script responsible for changing the text and the image does not work.
This is really baffling.
Have your return false inside Success and Error blocks.
Having it out will make that execute first and that may be the reason. alert() stops the execution of the script and that is why you see the expected if you have alert()
$(function() {
$("a#update").click(function(){
var curr_elem = $(this) ;
var link = $(this).attr("href");
$.ajax({
type: "POST",
url: link,
success: function()
{
var text = curr_elem.parent().parent().find('span#sent_text').text();
if (text == 'Completed')
{
curr_elem.parent().parent().find('span#sent_text').html('In complete');
curr_elem.parent().parent().find('IMG').attr("src", "/static/images/check.jpeg");
}
else
{
curr_elem.parent().parent().find('span#sent_text').html('Completed');
curr_elem.parent().parent().find('IMG').attr("src", "/static/images/unchecked.jpeg");
}
return false;
},
error: function(xhr, status, error)
{
alert("Function failed!");
return false;
}
});
});
});

CakePHP & JQuery, location.reload sometimes not working

Hi I am developing data deleting page with checkbox and button. After deletion, I'd like to display the message either the transaction is successful or not. Most of the time the message shows correctly, but sometimes the page reload doesn't happen and the message won't show until manually reloaded.
Now if it's not certain if the page is reloaded, is there any other way to show the message from the controller?
Here's the code:
(index.ctp)
<script type="text/javascript">
$(document).ready( function() {
$("#btn").click(function() {
var ids = '';
$('input[type="checkbox"]').each(function(){
if(this.checked){
ids = ids.concat(this.id).concat(',');
}else{
jAlert("Please choose items to delete");
}
});
if (ids != ''){
jConfirm('Delete?', 'Confirm',function(r){
if(r==true){
ht = $.ajax({
url: 'items/delete/'.concat(ids),
type: "POST",
contentType: "application/json; charset=utf-8",
});
location.reload(true);
}
});
}
});
});
</script>
(controller.php#function delete())
$this->Session->setFlash(__('Deleted!, true));
$this->redirect(array('action'=>'index'));
CakePHP's session flash is usually pretty reliable.
Perhaps your browser is not reliably doing a hard refresh with location.reload(true). Try window.location = window.location.href + "?nocache=" + new Date().getTime() to manually clear the cache and see if that helps at all.

Categories

Resources