I was wondering how do I cache results from the .load function in javascript, I'm loading a html file like the one below, what I want to be able to do is load the cache by Parent-ID then when each child-ID is called it doesn't have to reload the html file everytime.
<div id="provider1">
<div id="thumb1">
content1
</div>
<div id="thumb2">
content2
</div>
<div id="thumb3">
content3
</div>
</div>
And the javascript I've been using:
var titleID = $(this).attr('id');
$('#content').prepend('<div id="loading">load</div>')
.load('test.html #'+ titleID')
Thanks a lot
$.ajaxSetup ({
cache: true
});
var titleID = $(this).attr('id');
$('#content').prepend('<div id="loading">load</div>')
.load('test.html #'+ titleID')
Rewrite load logic like this:
if (stuff in localStorage) {
// take it from there
} else {
// load
// on complete, put stuff in localStorage
}
Check http://diveintohtml5.ep.io/storage.html. There is also jQuery.data(), you can do some simple caching with it too.
Related
I know this is a very concrete issue but I've struggled with this code for the last 2 hours and I can't find anything on the topic or figure out how to solve it.
I have an issue with a jQuery Ajax Post request. I am trying to make a section on my page where I display the users current level. When a user interacts and does something that increases the level on the site the level should also increase in the DOM/client's browser. Therefore I've added a setinterval that allows the request to run every 5th second. And if the $(response).text() is different from the current div's .text() where i am rendering the current level I want to append this new response from the ajax request.
Maybe the answer is more obvious than I think.... I have added the code below
Ajax page:
$(document).ready(function () {
function getLevel() {
var getLvlData = $.ajax({
url: "AjaxRequests.php",
type: "POST",
data: {type: "4", lvl_r_type: 1}
});
getLvlData.done(function (response, textStatus, jqXHR) {
var innerLevelHTML = $("#LevelContainer");
if (($(response).text()) != ($(innerLevelHTML).text())) {
innerLevelHTML.html("");
innerLevelHTML.append(response);
}
if ($(response).text() == $(innerLevelHTML).text()) {
alert("the same");
}
});
}
var levelChecker = setInterval(function () {
getLevel();
}, 1000);
getLevel();
});
AjaxRequests.php:
if ($_POST["type"] == "4" && isset($_POST["lvl_r_type"])) {
$returnVal = htmlentities($_POST["lvl_r_type"]);
if (!empty($returnVal)) {
if ($returnVal == 1) {
?>
<div id="chartWrapper">
<div>
<canvas id="doughnut-chart"></canvas>
</div>
<div id="chart-center">
<div>
<div><h1>0%</h1></div>
<div><p>GX 0 / 1</p></div>
</div>
<div><p>LVL 0</p></div>
</div>
</div>
<div id="progressList">
<div><p>View tasks</p></div>
</div>
<?php
}
}
}
?>
html page
<div id="LevelContainer"></div>
Try using trim since a white space could be treated as a part of the text.
if (($(response).text().trim()) != ($(innerLevelHTML).text().trim())) {
...
One alternative approach I can think of, off of my head is, to set a hash inside a data attribute say data-hash="" whenever you set the html of that div, and then whenever you have a new ajax response you can generate a hash on the fly and compare that to the existing one and if a change is found just update the html and the hash value for that attribute.
This process minimises the confusion that may be caused due to dom being updated by some script.
Also, Instead of
innerLevelHTML.html("");
innerLevelHTML.append(response);
Why not just just set the html directly as
innerLevelHTML.html(response);
if you want to understand my problem, please read every step of that shitty code that make me angry :
The context of all of this is an API, so I have to do an ajax call to an external JSon file. The call works : I get the response, and I can manage data like I wanna.
jQuery(function($) {
$.ajax({
url: 'http://MY JSON URL/',
contentType: "application/json; charset=windows-1252",
dataType: "json",
success: function(content) {
var api = content.contents.response // Dont care about this, it work.
var AnyDataFromJsonIWantToGet = api.data // Dont care about this, it work.
$('#myAPI').html("Some HTML content, syntax checked" +
$('#mainbuy').html()
+ "Some HTML content, syntax checked");
},
/* Error */
error: function(xhr, status, error){
alert("No Json" + xhr.status);
},
});
As you can see, I call $('#mainbuy').html() in $('#myAPI').html(). My problem is in $('#mainbuy').html() but occur only when called in $('#myAPI').html(). Here is the main page HTML code for $('#mainbuy').html(), I keep all my <div class> and others <div> cause maybe you will find the source of my problem in it, but you will see later why I think its absolutely not about my CSS tricks.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainbuy" style="display:none;">
<div class="coachbtn"><div class="dropup"><div id="buybtn">
<select class="selectpicker" data-style="btn-primary" id="pickhour" name="pickhour">
<option value="1">1H</option>
<option value="2" selected>2H</option>
<option value="3">3H</option>
<option value="4">4H</option>
</select>
</div></div></div>
<div class="coachbtn2"><div id="buybtn2">
<a id="egglink" class="button button-large" style="width: 260px">Reserver</a>
</div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#pickhour').change(function(){
pickhour1 = $(this).val();
$("#egglink").attr("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});
});
</script>
</div>
So, in this :
-A dropdown select-box : ID "pickhour"
-A button (<a></a> with style) : ID "egglink"
My script used to get the .val() of selected value in my select-box, and put it in a link which is .attr() href to my button.
The problematic :
If I show the select box + the button + the script in my main page without calling it elsewhere : It works fine !
If I want to show <div id="mainbuy" style="display:none;"> with $('#mainbuy').html() in $('#myAPI').html() : The result is showing every elements like it should but the script dont work, no HREF on my button.
I dont know if it is important but I use Fancybox to open $('#myAPI').html() :
<div id="openAPI" style="display:none;width:auto;height:auto;">
<div id ='myAPI'>
</div></div>
<a class="hover-wrap fancybox-media" data-fancybox-group="video" title=" " href="#openAPI">
Im not really smart with JavaScript and actually Im lost in this, it seem to be easy and working, but its not.. :(
Thanks you for readind, I hope someone here can help me.
Maybe your DOM is not updated (cause your AJAX request), try this :
$('#buybtn2').on('change' , '#pickhour' , function(){
pickhour1 = $(this).val();
$("#egglink").attr("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});
I don't know if that work..
Sorry in advance for my bad english.
it's not "#buybtn2" but "#buybtn" sorry for that.
Actually, you try to change href attribute, but this button doesn't have any href attribute. Maybe it's that your problem.
try to add a href at your button :
<div class="coachbtn2">
<div id="buybtn2">
<a id="egglink" class="button button-large" href="" style="width: 260px">Reserver</a>
</div>
</div>
For the newest versions of jquery attr refers to the originally html. So changing it won't update the DOM. Try using prop instead.
$('#buybtn2').on('change' , '#pickhour' , function(){
pickhour1 = $(this).val();
$("#egglink").prop("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});
This question has been asked on a few occasions, for example:
Store Cloned Element in Variable
Copy DOM Element
However, I'm having issues selecting say <div id="XYZ"></div> and cloning it to a variable for the jQuery DataTable fnStateSaveParams to save. When the page refreshes it is then meant to reload the cloned object back into the HTML via fnStateLoadParams. I am trying to use .clone() over .html() because I also need the values stored within the dynamically generated textboxes.
If I'm not saving and loading via the Datatables plugin, then it works perfectly. As soon as I try calling code similar to the below then it ceases to work (please bare in mind I've tried a number of variations to the below code). Has anyone got any ideas or suggestions?
"fnStateSaveParams": function (oSettings, oData) {
var clonedHtml= $("#XYZ").clone(true);
oData.storedHtml = clonedHtml;
},
"fnStateLoadParams": function (oSettings, oData) {
//$("#displayHtml").append(oData.storedHtml);
//$("#displayHtml").html(oData.storedHtml);
//$(oData.storedHtml).prependTo("#displayHtml")
}
<div id="XYZ">
<div data-template="">
<label class="bolder"></label>
<div class="input-append">
<div class="inline-block advancedSearchItem">
<input type="text" id="test1" value="Test Scenario" />
</div>
<a href="#" data-id="" class="btn btn-small btn-danger removeField">
<div class="hidden-phone">Remove</div>
<i class="icon-trash icon-only hidden-tablet hidden-desktop"></i>
</a>
</div>
</div>
</div>
The end scenario will be more complex, however the above is the simplest form of what I am trying to create. If you need more information, feel free to ask and I'll update the question accordingly.
I didn't find a way of utilising .clone() to grab all HTML and Text Box values. However, I did come up with a solution and the code below is for anyone who needs a reference point.
Using .html() (as most will know) will only copy the available HTML and ignore what is essentially 'placeholder' text within text fields. My solution though is to force the value into the HTML rather than being treated as 'placeholder' text, this allows it to be used again when the page is loaded.
$(document).on("click", "#advancedSearchButton", function(event) {
event.preventDefault();
// DO SOME STUFF HERE
$("[data-value]").each(function(index) {
if (index > 0) {
fieldCount++;
$(this).attr("value", $(this).val());
}
});
oTable.fnFilter("");
});
function loadData() {
// ... ... ...
"fnStateSaveParams": function(oSettings, oData) {
oData.advancedSearchHtml = $("#addedSearchFields").html();
oData.fieldCount = fieldCount;
oData.isAdvancedSearch = isAdvancedSearch;
},
"fnStateLoadParams": function(oSettings, oData) {
$("#addedSearchFields").html(oData.advancedSearchHtml);
if (oData.isAdvancedSearch == true) {
$("#collapseElement").removeClass("collapsed");
$("#collapseIcon").removeClass().addClass("icon-chevron-up");
$("#filter").hide();
}
isAdvancedSearch = oData.isAdvancedSearch;
advancedSearchFields = oData.fieldCount;
}
// ... ... ...
}
Please forgive my awful coding style. I am learning to write a Chrome extension and can't figure out some JQuery stuff. I am trying to parse a document with some rows, each containing a (dynamically generated?) link, the HTML code looks like this:
<div class="row" id="rand">
<div class="display">
<div class="link">
<a name="actionLink" href="#" alt="action" onclick="listener.postAction('form', 'http://***/')" class="alink"><span>Confirm</span></a>
</div>
</div>
I am grabbing the info the following way:
$(".row").each(function(index)
{
var $itemArea = $(this).find(".display");
var id = $(this).attr("id");
var alink = $(this).find(".link").find("a");
var onclick = alink.attr("onclick");
console.log("id=" + id);
console.log("alink=" + alink);
console.log("onclick=" + onclick);
});
Here's the output from JSBin:
"id=rand"
"alink=[object Object]"
"onclick=listener.postAction('form', 'http://***/')"
However, when I debug this in Chrome, the value of "onclick" returned by my code is undefined. To make things more confusing, when I inspect the onclick attribute of alink, it shows the correct value? What am I doing wrong?
Try the following to get your var instead
var onclick = $('.link a:first',this).attr('onclick');
The idea is: i have a main DIV with content mini divs of cars info divided two per row, that i'm getting with a query from DB, i want when pressing that button to make reload of that main content with new content from the DB, is that possible to do ? please advise.
code looks like this:
<div class="SearchBlocks">
<div class="row">
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
......
</div>
<h2 class="load_more"><a id="more_link" href="#">Load more <i class="icon-custom_arrow"></i></a></h2>
</div>
function reload(url){
$.get(url, function(data){ // $.get will get the content of the page defined in url and will return it in **data** variable
$('#row').append(data);
}
}
$('#more_link').click(function(e){
e.preventDefault();
var url = 'http://example.com/somepage.html';
reload(url); // this calls the reload function
});
You haven't shown the exact code you're using to generate your AJAX request, however the general pattern will be something like this, where the update logic is extracted in to it's own function which is called both on load of the page, and click of the #reload_cars button.
function getData() {
$.ajax({
url: 'yoururl.foo',
success: function(data) {
$('#row .car_section').remove();
$('#row').append(data);
}
});
}
$('#reload_cars').on('click', getData);
getData();
just use
function refreshDiv(){
var container = document.getElementById("divId");
var content = container.innerHTML;
container.innerHTML= content;
}