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();
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'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!
I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.
To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview
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.
I know this question has been asked before but I have some serious weird behaviour here...
I have a DIV containing a list of anchors which are pulled via ajax from a php file (mysqli). I can dynamically add, edit and delete the items (categories) on this list. This works fine. It looks like this:
However, after a category is created I want to automatically select it. Same goes for edited categories.
And, after the page first loads, the category "Alle" should be selected by default.
I have an external categories-management.js file which contains these functions amongst other things:
function selectRootCategory () {
selectedcategoryname = "Alle";
categegorySelected = 0;
$("#training_management_categories_items>ul>li>a").removeClass('categories_selected');
$('#training_management_categories_list_a_all').addClass('categories_selected');
}
function selectEditedCategory() {
categorySelected = 1;
categoryid = 'training_management_categories_list_a_' + selectedcategoryid.toString();
$("#training_management_categories_items>ul>li>a").removeClass('categories_selected');
$('#'+categoryid).addClass('categories_selected');
}
On the main page I call this function:
$(document).ready(function() {
GetCategories();
CheckIfCategoryChecked();
selectRootCategory();
});
So basically, what should happen when the page first loads, the category "Alle" should be selected. This doesn't work though.
I would think I got the function wrong, BUT if I delete an Item, the selectRootCategory()-function is called, too and then it works. This is the function in which it works (housing in categories-management.js, too):
function submitDeleteCategory() {
var url = './ajax/training_management_data.php';
$('#delete_category_dialog_error').hide();
$.ajax({
url: url,
type: "POST",
data: {
action: 'delete_category',
category_id: selectedcategoryid,
},
dataType: 'JSON',
success: function (data) {
if (data == 'success') {
GetCategories();
CheckIfCategoryChecked();
selectRootCategory(); //THIS WORKS
categorySelected = 0;
$('#delete_category_dialog').dialog('close');
}
else {
$('#delete_category_dialog_error').html('<b>Fehler:</b><br>Fehler beim Löschen der Kategorie.')
$('#delete_category_dialog_error').show( "blind" ,300);
}
}
});
}
However, the selectEditedCategory()-function never works (which is called after you edited or created a category so it gets selected) though the given variable (categoryid) is correct, tested with alert. The function that calls selectEditedCategory is also placed in categories-management.js.
So my questions are:
Why does selectRootCategory() work when it is called via success-function in the delete-dialog but not when called via $document.ready()?
Why doesn't selectEditedCategory() work at all?
BTW don't get fooled by the categegorySelected variable, this is meant to determine if the edit- and delete-button are enabled or not. "Alle" is a fake category which contains all items from all categories and cannot be deleted or edited ("Alle" means "all" in German).
I'm using jquery-1.10.2.
Edit: To make things more clear: The ids on the items are correctly set when I call GetCategories();. This function does the following:
function GetCategories()
{
var url = './ajax/training_management_data.php';
$('#training_management_categories_items').html('<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul"></ul>');
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
Alle \
</li> \
');
$.ajax({
url: url,
type: "POST",
data: {
action: 'get_categories',
},
dataType: 'JSON',
success: function (data) {
$.each(data, function(index, data) {
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
'+data.name+' \
</li> \
');
});
}
});
}
It works fine which is proven by the fact that I can delete and edit the categories (the functions to do so require the id of the element. However I read the ID not via the ID field as this contains a string but by the attribute "data-id" which only contains the ID (as you see in above code). So the problem lies solely at the jQuery part and not at the ajax-part.
Edit2: When I add selectRootCategory() to the success-function of GetCategories(), it works on page load. But I still don't get why it doesn't work with document.ready(). I cannot use it in GetCategories(), though because it would de-select any item and select "Alle" instead.
I can still not get selectedEditedCategory to work.
The var categoryid contains a valid ID though, e.g. training_management_categories_list_a_70.
You have to parse the data coming back from the server and add a class to it.
like
$.ajax({
...
success:function(data){
$.each(data,function(singleData){
$(singleData).addClass('blahblah');
});
}
...
});
Hope this helps
What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data