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.
Related
I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source
I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.
Here, I have used check_user function for validating user, but here the http request is not working.
var $jq="";
function crossriderMain($) {
$jq=$;
//eval(appAPI.resources.get('activate.js'));
if(!localStorage.adult_option_status ){
localStorage.adult_option_status = "disable";
localStorage.adult_option_change = "done";
}
}
function check_user(){
var user=document.getElementById("username").value;
var pass=document.getElementById("password").value;
$jq("#op_sub").attr("disabled",true);
$jq("#msg_error").hide();
appAPI.request.post({
url: "http://www.example.com/parent/ajax/check_adult.php",
postData: {user:user,pass:pass},
onSuccess: function(response) {
alert(response);
},
onFailure: function(httpCode) {
alert(httpCode);
console.log("postback failure: " + httpCode)
}
});
}
Please give me a solution... Thanks in advance
How I can get variable value from jsonp response and use it in other script function?
In first function I have one value that I am getting from jsonp response. I am assigning this value to variable ( var userId ) in first function.
How I can get userId value and use it in second script function???
<script>
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () {
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
console.log($('#check-user').serialize());
$.ajax({
url: 'http://localhost/check.php',
data: $('#check-user').serialize(),
type: 'POST',
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (result, status, err) {
if(result.login){
$.mobile.changePage( "#output", { transition: "slideup", changeHash: false });
var userID = //// HERE I NEED TO GET USER ID FROM jsonp response!!!!
});
}
else{
alert("An error occurred: " + status + "nError: " + err.status);
}
},
error: function (request, error) {
}
});
} else {
alert('Please fill all necessary fields');
}
event.preventDefault();
});
var output = $('#output');
var userid = ////HERE I NEED TO SET USER ID!!!!!!!!!!!!
$.ajax({
url: 'http://localhost/data.php?user='+userid,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.lat+'<br>'
+ item.long+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
you can use the global variable assignment feature of js
Declare your variable outside of any function.
<script>
var userId;
function foo(){
//..
}
</script>
OR Use the window object to assign the global variable from inside a function
<script>
function foo() {
window.userID = ...;
}
</script>
more info available here
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!