I am using following code to fetch and cache data from a ASP.NET handler. The problem is that whenever I cache data using a button click its working fine, but I want this to happen at document.ready() event. When I executed this code on document.ready() event, its fetching data perfectly, but its not getting data from the cache when I reload the page.
var localCache = {
data: {},
remove: function (url) {
delete localCache.data[url];
},
exist: function (url) {
return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
},
get: function (url) {
console.log('Getting in cache for url' + url);
return localCache.data[url];
},
set: function (url, cachedData, callback) {
cacheTime = (new Date()).getTime();
localCache.remove(url);
localCache.data[url] = cachedData;
if ($.isFunction(callback)) callback(cachedData);
}
};
var now;
var cacheTime;
var tDiff;
function getValueAtIndex(index) {
var str = window.location.href;
return str.split("/")[index];
}
//$(document).ready(function () {
$('#Button1').click(function (e) {
var url = '/Handlers/ResponseFetcher.ashx';
var topicid = "<%=desid %>";
$.ajax({
url: url,
type: "POST",
data:
JSON.stringify({ tid: topicid })
,
dataType: "json",
cache: true,
beforeSend: function () {
now = (new Date()).getTime();
if (localCache.exist(url)) {
tDiff = now - cacheTime;
if (tDiff < 20000) {
loadData(localCache.get(url));
return false;
}
}
return true;
},
complete: function (jqXHR, textStatus) {
localCache.set(url, jqXHR, loadData);
}
});
});
function loadData(data) {
console.log("now: " + now + ", cacheTime: " + cacheTime + ", tDiff:" + (cacheTime - now));
$('#responseloader').hide();
var resdata = JSON.parse(data.responseText);
$(resdata).each(function (i) {
$('#responsecontainer').append("<div>" + this.Title + "</div>");
});
}
Here tDiff will be undefined on first run. Is this the problem? or caching doesn't work if the page is reloaded? Please help!
Related
I have the following code that causes "ERR_INSUFFICIENT_RESOURCES" in my Chrome browser.
I thought about to replace the setInterval() function with setTimeout().
Do you think it would be a better idea to use setTimeout ?
Or do you have an idea how to improve my script ?
<script>
$(function () {
setInterval(function () {
$.ajax({
type: "GET",
url: "/Home/UpdateDBentries",
success: function (response) {
$("#updTotalDBentries").html(response.result);
},
failure: function (response) {
//alert("Failure: [Index] - UpdateDBentries: " + response.responseText);
},
undefined: function (response) {
//alert("Undefined: [Index] - UpdateDBentries: " + response.responseText);
},
error: function (response) {
//alert("Error: [Index] - UpdateDBentries: " + response.responseText);
}
});
}, 2000);
});
</script>
// Working
public JsonResult UpdateDBentries()
{
// This way is much faster then using "Count()"
int? DbEntriesResult = entities.Measurement.Max(u => (int?)u.id);
return Json(new { result = DbEntriesResult }, JsonRequestBehavior.AllowGet);
}
I expect no ERR_INSUFFICIENT_RESOURCES.
Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.
I am attempting to do an AJAX call with the Select2 jquery plugin. The query seems to be working, but the issue occurs when .results() is called on the options object:
Uncaught TypeError: options.results is not a function
Here is my HTML:
<input class="form-control" type="number" value="2125" name="topic_relation[source_topic_id]" id="topic_relation_source_topic_id" />
Here is my JS:
$(document).ready(function() {
$('#topic_relation_source_topic_id').select2({
minimumInputLength: 3,
ajax: {
url: "<%= grab_topics_path %>",
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
q: term, //search term
page_limit: 30, // page size
page: page, // page number
};
},
processResults: function (data, page) {
var more = (page * 30) < data.total;
return {results: data.topics, more: more};
}
},
formatResult: topicFormatResult,
formatSelection: formatRepoSelection,
escapeMarkup: function (m) { return m; }
});
function topicFormatResult(topic) {
return topic.name
}
function formatRepoSelection(topic) {
return '<option value="'+ topic.id +'">' + topic.name + '</option>'
}
});
Here is the returned JSON:
{"total":2, "topics":[{"id":305,"name":"Educational Assessment, Testing, And Measurement"},{"id":3080,"name":"Inspectors, Testers, Sorters, Samplers, And Weighers"}]}
Here is the code which is failing:
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler && typeof handler.abort === "function") { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
========> var results = options.results(data, query.page, query); <==========
query.callback(results);
},
error: function(jqXHR, textStatus, errorThrown){
var results = {
hasError: true,
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
};
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
Since the plugin calls results(), you should also declare results: function (data, page) instead of processResults: function (data, page).
So I am writing something using augment for inheritance and for some reason I can run this.setButtons(type) and console.log(this.buttons) in that method, but when I run my this.getButtons() it comes back as undefined, even though getButtons just returns this.buttons. Any help would be greately appreciated. I will post up all the code I have so far, because maybe I'm not inheriting properly. Thank you in advance.
var ContextMixin = function () {};
ContextMixin.prototype = {
createElements: function (el, mode, type) {
var m;
if (mode == 'exact') {
$("#" + el).append("<ul id='contextmenu'>");
} else {
$(el).each(function () {
m = $(this).append("<ul id='contextmenu'>");
});
$('body').append(m);
}
$("#contextmenu").css({
'position': 'absolute',
top: 13,
left: 13
});
var new_buttons = this.getButtons();
$.each(this.buttons['buttons'], function () {
m.append("<li id='" + this + "'>" + this + "</li>");
});
},
attachEvents: function () {
functions = this.getFunctions(type);
buttons = this.getButtons();
for (index in buttons['buttons']) {
addEvent(buttons['buttons'][index], this.functions[index][0], this.functions[index][1]);
};
},
setFunctions: function (type) {
var callback = {
success: function (msg) {
this.functions = msg;
},
failure: function () {
alert('Error getting functions')
}
};
$.ajax({
type: 'GET',
url: 'function_list.php?type=' + type,
success: function (msg) {
this.functions = msg;
}
});
},
getFunctions: function () {
return this.functions;
},
setType: function (value) {
this.type = value;
},
getType: function () {
return this.type;
},
setButtons: function (type) {
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function (reply) {
this.buttons = reply;
}
});
},
getButtons: function () {
return this.buttons;
}
}
function createMenu(el, type, mode) {
this.setButtons(type);
this.setFunctions(type);
this.createElements(el, mode, type);
}
augment(createMenu, ContextMixin);
function augment(receivingClass, givingClass) {
if (arguments[2]) { //Only give certain methods.
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else { //Give all methods
for (methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
Because this in the callback to the AJAX request is not your object.
Here's a common fix...
setButtons: function(type) {
var self = this; // keep a reference to this
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
self.buttons = reply; // use the reference here
}
});
},
...but a better fix is to use the context: property of the $.ajax request...
setButtons: function(type) {
$.ajax({
type: 'GET',
context: this, // set the context of the callback functions
url: 'button_list.php?type=' + type,
success: function(reply) {
this.buttons = reply;
}
});
},
If you change
ContextMixin.prototype = {
createElements
to
ContextMixin.prototype.createElements
it should work.
this is not what you think it is in your ajax callback—instead of being your current object, it's actually the global object the XHR object. All your callback is doing is putting a buttons property onto the xhr object.
You need to save this before your function runs:
setButtons: function(type) {
var self = this;
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
alert(reply);
self.buttons = reply;
}
});
},
I have this functions
//send JSON-RPC request
var json_rpc = (function() {
var id = 1;
return function(url, method, params, success) {
if (typeOf(params) != 'array') {
params = [params];
}
var request = JSON.stringify({
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': id++});
return $.ajax({
url: url,
data: request,
success: success,
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_msg('XHR error ' + XMLHttpRequest.status + ' ' +
XMLHttpRequest.responseText);
},
beforeSend: function(xhr) {
console.log('before send');
console.log(dir(xhr));
xhr.onreadystatechange = function(){
console.log('state');
};
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
})();
var rpc = function(method, success_callback) {
//I use functional javascript library
var fun = json_rpc.partial('rpc.php', method, _, function(data) {
if (data['error']) {
var e = 'Json-RPC (' + method + ') ' + data['error']['code'] + ": " +
data['error']['message'];
error_msg(e);
} else {
info_msg("rpc sucess for method '" + method + "'");
success_callback(data['result']);
}
});
return function() {
fun(Array.slice(arguments));
};
};
and when I create function with rpc
var update_news = rpc('get_news', function(data) {
if (data) {
//update news
}
});
and call it
$(document).ready(function() {
...
update_news();
...
});
In Firefox everythig is fine, but in Opera and Chrome the function update_news is not executing, beforeSend is fired but onreadystatechange is not, but when I add
setTimeout(update_news, 0);
Then It's call normaly, also when I create synchronous call by putting async: false in $.ajax call or when I put timeout, timeout: 1. In click handlers it also run as expected.
$('#some_id').click(function() {
update_news();
});
Anybody know why this is happening.