Event Handler to run only when previous event handling is complete - javascript

Attached Event handler to callback like :
$("someSelector").on('click',callBackHandler);
function callBackHandler(){
//Some code
$.ajax({
//Ajax call with success methods
})
}
My success method is manipulating some object properties. Since ajax is involved, it will not wait for the completion and next event handling will start. How can I make sure next click event handling starts only when previous handling is done.
Cannot think of a way of using deferred manually on this because I am triggering event manually on base of some condition in for loop (Not a clean style of coding, but has no other option in particular use case).
$('someSelector').trigger('click');

$("someSelector").on('click', function(event) {
event.preventDefault();
var urAjax = $.ajax({
// Ajax Call here...
});
urAjax.always(function(response) {
$.when( callBackHandler() ).done(function() {
// Handle your ajax response in here!
});
});
});
function callBackHandler() {
// Do Stuff
}
callBackHandler function will fire, and when it's done, your ajax response for .always will fire directly after that. This allows for your ajax to load while the callBackHandler function is running also, but doesn't fire the response until after the function is done! Hopefully I'm understanding what you are asking for here.
You can see an example jsfiddle located here: https://jsfiddle.net/e39oyk8q/11/
Try clicking the submit button multiple times before the AJAX request is finished, you will notice that it will loop over and over again the total amount of clicks you give it on the Submit button. You can see this by the amount of times the Alert box pops up, and also, it adds 100 to the len (that gets outputted on the page) during each call to the callBackHandler function. So, I do believe this is what you asked for.
And, ofcourse, you can still use: $('someSelector').trigger('click');
EDIT
Another approach is to return a json object that can be used within the ajax call or wherever you need it within the click event, like so:
$("someSelector").on('click', function(event) {
event.preventDefault();
var myfunc = callBackHandler();
var urAjax = $.ajax({
type: 'POST',
url: myfunc['url'],
data: myfunc['data']
});
urAjax.always(function(response) {
$.when( myfunc ).done(function() {
console.log(myfunc['time']);
// Handle your ajax response in here!
});
});
});
function callBackHandler() {
var timestamp = new Date().getTime();
return { url: 'my_ajax_post_url', data: {data1: 'testing', data2: 'testing2'}, time: timestamp }
}
fiddle example here: https://jsfiddle.net/e39oyk8q/15/

You can remove the binding on the call of function and bind again when the ajax is done().
function callBackHandler(){
$("someSelector").off('click');
//Some code
$.ajax({
//Ajax call with success methods
}).done(function(){
$("someSelector").on('click',callBackHandler);
})
}

var requestDataButton = document.querySelector('.js-request-data');
var displayDataBox = document.querySelector('.js-display-data');
var displayOperationsBox = document.querySelector('.js-display-operations');
var displayNumberOfRequestsToDo = document.querySelector('.js-display-number-of-requests-to-do');
var isAjaxCallInProgress = false;
var numberOfAjaxRequestsToDo = 0;
var requestUrl = 'http://jsonplaceholder.typicode.com/photos';
requestDataButton.addEventListener('click', handleClick);
function handleClick() {
displayNumberOfRequestsToDo.innerText = numberOfAjaxRequestsToDo;
numberOfAjaxRequestsToDo++;
if(!isAjaxCallInProgress) {
isAjaxCallInProgress = true;
requestData();
}
}
function handleResponse(data) {
displayData(data);
displayOperationsBox.innerHTML = displayOperationsBox.innerHTML + 'request handled <br>';
numberOfAjaxRequestsToDo--;
displayNumberOfRequestsToDo.innerText = numberOfAjaxRequestsToDo;
if(numberOfAjaxRequestsToDo) {
requestData();
} else {
isAjaxCallInProgress = false;
}
}
function displayData(data) {
displayDataBox.textContent = displayDataBox.textContent + JSON.stringify(data[0]);
}
function requestData() {
var request = new XMLHttpRequest();
request.open('GET', requestUrl, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
handleResponse(data);
} else {
// on error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
displayOperationsBox.innerHTML = displayOperationsBox.innerHTML + 'request sent <br>';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="js-request-data">Request Data</button>
<div>
<h2>Requests wainting in a queue to be sent:
<span class="js-display-number-of-requests-to-do">
0
</span>
</h2>
</div>
<div>
<h2>Operations:</h2>
<div class="js-display-operations"></div>
</div>
<div>
<h2>Response Data:</h2>
<div class="js-display-data"></div>
</div>
edit
here's a utility function that takes similar arguments as $.ajax, and then returns an augmented $.ajax function that keeps an eye on its previous calls and waits for all preceding requests to finish before dispatching another ajax call (are fired sequentially):
function sequentialize(requestData, responseHandler) {
let inProgress = false;
let deferredRequests = 0;
const makeRequest = () => {
$.ajax(requestData).then(processManager);
};
const processManager = (data) => {
responseHandler(data);
if (deferredRequests) {
deferredRequests--;
makeRequest();
} else {
inProgress = false;
}
};
return function () {
if (!inProgress) {
inProgress = true;
makeRequest();
} else {
deferredRequests++;
}
};
}

Related

A JavaScript function is repeated many times

I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.
function print(url) {
console.log('print');
var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
if ($iframe.attr('src') != url) {
$.when(
$iframe.attr('src', 'about:blank'),
$iframe.load(function () {
console.log($iframe.prop('contentWindow').document.readyState);
})
).done(function () {
$iframe.attr('src', url);
$iframe.load(function () {
console.log('new');
_this.callPrint(iframeId);
});
});
} else {
console.log('old');
_this.callPrint(iframeId);
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
console.log('callPrint');
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
return false;
}
A JavaScript function is repeated many times
The problem is because you're attaching two new load() event handlers to the iframe every time print() is called. To fix this, add a single load() event handler and call your function from in there. This will be triggered whenever you update the src attribute on the element. Try this:
var $iframe = $('#iframeprint').load(function() {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
callPrint('iframeprint');
});
function print(url) {
var _this = this;
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
_this.callPrint(iframeId);
}
}
Thanks "Rory McCrossan". I add setTimeout function when callPrint so dialog print will open. But I can't vote for you at the moment.
var $iframe = $('iframe#iframeprint').load(function () {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
setTimeout(function () {
callPrint('iframeprint');
}, 100);
});
function print(url) {
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
console.log('old');
callPrint('iframeprint');
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
}

Why my JavaScript function is executing uncertainly if i add an alert()?

I wrote the function below to get the length of a listbox with the id courselessons. The problem is that when I comment the alert() the function changecheckbox works only once.
If I remove the alert it works fine. But I don't want to have an alert on every single click.
The selOpts shows correct content only for the first time.
JavaScript:
function changecheckbox() {
//alert("function called...");
var selOpts = document.getElementById("courselessons").length();
alert(selOpts);
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop('disabled', true).prop("checked", false);
}
}
function addItem() {
if (seltask == undefined || seltask.length === 0) {
return;
}
var lessonsDropdown = $('#courselessons');
lessonsDropdown.empty();
$("#tasks option:selected").appendTo("#coursetasks");
$("#coursetasks option").attr("selected", false);
if (seltask.length > 0) {
cacheToken = new Date().getTime();
// retrieve data using a Url.Action() to construct url
$.getJSON('#Url.Action("AddTaskToCourse")', {
task: seltask,
lesson: lesson,
_: cacheToken
});
$.getJSON('#Url.Action("UpdateLessonInCourse")', {
_: cacheToken
}).done(function (data) {
//re-enable tasks drop down
//for each returned tasks
$.each(data, function (i, lessons) {
//Create new option
var test = $('<option />').html(lessons);
//append tasks taskss drop down
lessonsDropdown.append(test);
});
seltask = null;
});
}
changecheckbox();
}
HTML:
<button type="button" id="btnAdd" onclick="addItem(); changecheckbox();">Add Item</button>
Try using like this,
function changecheckbox() {
//alert("function called...");
var selOpts = $("courselessons").find('option').length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop({'disabled':true, 'checked':false});
}
}
or you can do like this ,
$("#btnAdd").click(function(e){
e.preventDefault();
var selOpts = $("#courselessons").find('option').length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop({'disabled':true, 'checked':false});
}
});
The code inside addItem() is making a GET request to a resource asynchronously. This means the code which comes after this function to be execute will not wait for its execution to get complete.
When I uncomment the alert it works fine.
That is because as the alert() is built in, it halts the execution of script until user interaction. This gave the time addItem() needs and everything seems to work.
Fortunately, there are solutions available to handle this situation.
Promise.
Rearrange your code to work with callbacks.
Under the covers, $.getJSON is shorthand for making a GET request using ajax with datatype = 'json'and it returns a promise object which basically tells that please wait honey, i will give you something which could be a success or a failure but sometime later.
So yes, you can easily call the function inside the done().
NOTE: These things have been explained pretty well on web so i will not reinvent the wheel :)
Keeping the things simple...
function addItem() {
// Rest of the code...
if (seltask.length > 0) {
cacheToken = new Date().getTime();
// retrieve data using a Url.Action() to construct url
$.getJSON('#Url.Action("AddTaskToCourse")', {
task: seltask,
lesson: lesson,
_: cacheToken
});
$.getJSON('#Url.Action("UpdateLessonInCourse")', {
_: cacheToken
}).done(function (data) {
//re-enable tasks drop down
//for each returned tasks
$.each(data, function (i, lessons) {
//Create new option
var test = $('<option />').html(lessons);
//append tasks taskss drop down
lessonsDropdown.append(test);
});
seltask = null;
changecheckbox();
});
}
}
After this setup, you should remove the changecheckbox() call from the button onclick otherwise it would make it execute twice.
Remove the options, and take the id of select <select id="mySelect"> example:
var selOpts = document.getElementById("mySelect").length;
and your code will be
function changecheckbox() {
//alert("function called...");
var selOpts = document.getElementById("courselessons").length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop('disabled', true);
$("#taskassignment").prop("checked", false);
}
}

Alternative to AJAX async: false option for form submit button click event handler

I have a login form where we make an AJAX call to the server to perform a bit of validation before letting the login form continue submitting. The current code is outlined below:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
if (username.length <= 0) {
return false;
}
var userIsValid = false;
$.ajax({
async: false,
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
return userIsValid;
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
$(".loginButton").on("click", function (e) {
$errorMessageLabel.hide();
if (isUserValid($usernameTextbox.val())) {
return true;
} else {
$errorMessageLabel.show();
$errorMessageLabel.html(errorMessageHtml);
}
e.preventDefault();
return false;
});
})(jQuery);
I know that async: false is something that shouldn't be used since it's going out of style. My question is: What's the alternative. My click event handler needs to return true or false, meaning it has to wait for the ajax call to complete. If async: false is no longer an option, then the isUserValid method is going to return immediately without properly setting the userIsValid bool.
Now I can inline the ajax method call straight into the click event handler that's called on $(".loginButton"), but the same problem presents itself: It needs to either return true, or prevent default (i.e. prevent login) and return false depending on the result of the ajax call. Is there a way I can force the click event handler to wait for the result of the ajax call before returning, without using async: false? I understand there's a jQuery when() method, but I don't know if I can use that in this situation.
First thing, a form can be submited without clicking on respective submit button. So bind instead submit event to the form. Now depending ajax request result, you can submit the form, using e.g:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
$errorMessageLabel.hide();
if (username.length <= 0) {
return false;
}
var userIsValid = false;
// return the promise from ajax method
return $.ajax({
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
// "form:has(.loginButton)" or whatever more relevant selector
$("form:has(.loginButton)").on("submit", function (e) {
$errorMessageLabel.hide();
isUserValid($usernameTextbox.val())).always(function(validationResult ){
if(validationResult && validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(errorMessageHtml).show();
}
}.bind(this));
e.preventDefault();
});
})(jQuery);
A. Wolff's answer is the answer I accepted, but I wanted to share my final code solution based off their input as well as the various comments made back and forth.
(function ($) {
"use strict";
var $usernameTextbox = $("#UserName");
var $passwordTextbox = $("#Password");
var $errorMessageLabel = $(".errorMessageContainer");
$("form").on("submit", function (e) {
$errorMessageLabel.hide();
var username = $usernameTextbox.val();
if (username.length <= 0 || $passwordTextbox.val().length <= 0) {
return; // Server posts back with "username/password required" so we don't handle it here.
}
$.get("/myAjaxCall?username=" + username).done(function (validationResult) {
if (validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(validationResult.ErrorMessage).show();
}
}.bind(this)).fail(function() {
$errorMessageLabel.html("Error contacting server. Please try again.").show();
});
e.preventDefault();
});
})(jQuery);

jQuery Find and Replace is Hanging up the browser! Data size too big?

With alot of help from #kalley we have found out that If I comment the following two lines out the LAG is gone!
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
But how do I keep the above but cancel out the LAG ?
MORE INFO:
The code below works but the problem is that the $.GET is causing the browser to hang until the ajax request completes. I need (flow control?) or something that will solve this problem without locking/hanging up the browser until ajax completes the GET request.
The biggest LAG/Lockup/Hang is at $.get("updatetable.php", since the others only return 7 or less (number) values and this one ('updatetable.php') returns alot more (200-300kb). I would like to implement some sort of flow control here or make the script wait like 5 secs before firing the update command for tablesort and before showing the toast message so that ajax has time to GET the $.get("updatetable.php"data I just don't understand why does it lockup the browser as it is getting the data? is it trying to fire the other commands and that's whats causing the LAG?
Here are the STEPS
1.
$.get("getlastupdate.php" Will fire every 10 secs or so to check if the date and time are the same the return data looks like this: 20130812092636 the format is: YYYmmddHHmmss.
2.
if the date and time are not the same as the last GET then $.get("getlastupdate2.php" will trigger and this data will be send back and placed into a toast message and dispalyed to the user $().toastmessage('showNoticeToast', Vinfoo);
3.
before or after the above ($.get("getlastupdate2.php") another GET will fire: $.get('updatetable.php' this will GET the updated table info. and replace the old one with the new info. and then update/resort the table
4.
at the end of it all I want to $.get("ajaxcontrol.php" and this will return a 1 or 2 if the user is logged in then it will be a 2 else it's a 1 and it will destroy the session and log the user out.
<script type="text/javascript" src="tablesorter/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.widgets.js"></script>
<script type="text/javascript" src="tablesorter/final/toastmessage/jquery.toastmessage-min.js"></script>
<script type="text/javascript" src="tablesorter/qtip/jquery.qtip.min.js"></script>
<script type="text/javascript">
var comper;
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 2000);
});
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $table = $("table.tablesorter");
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
$tableContents.replaceWith('<tbody>' + data + '</tbody>')
//$tableContents.replaceWith($html)
$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$(function () {
var tid = setTimeout(checkComper, 2000);
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
// call the tablesorter plugin
$("table.tablesorter").tablesorter({
theme: 'blue',
// hidden filter input/selects will resize the columns, so try to minimize the change
widthFixed: true,
// initialize zebra striping and filter widgets
widgets: ["saveSort", "zebra", "filter"],
headers: {
8: {
sorter: false,
filter: false
}
},
widgetOptions: {
filter_childRows: false,
filter_columnFilters: true,
filter_cssFilter: 'tablesorter-filter',
filter_filteredRow: 'filtered',
filter_formatter: null,
filter_functions: null,
filter_hideFilters: false, // true, (see note in the options section above)
filter_ignoreCase: true,
filter_liveSearch: true,
filter_reset: 'button.reset',
filter_searchDelay: 300,
filter_serversideFiltering: false,
filter_startsWith: false,
filter_useParsedData: false
}
});
// External search
$('button.search').click(function () {
var filters = [],
col = $(this).data('filter-column'), // zero-based index
txt = $(this).data('filter-text'); // text to add to filter
filters[col] = txt;
$.tablesorter.setFilters($('table.hasFilters'), filters, true); // new v2.9
return false;
});
});
</script>
Maybe instead of using setInterval, you should consider switching to setTimeout. It will give you more control over when the time repeats:
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 10000);
});
}
var tid = setTimeout(checkComper, 10000);
Then you can keep it async: true
Here's a fiddle showing it working using echo.jsontest.com and some fudging numbers.
Since the click event callback seems to be where the issue is, try doing this and see if it removes the lag (I removed other comments to make it more brief):
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $tableContents = $table.find('tbody')
//var $html = $('<tbody/>').html(data);
//$tableContents.replaceWith($html);
// replaceWith text seems to be much faster:
// http://jsperf.com/jquery-html-vs-replacewith/4
$tableContents.replaceWith('<tbody'> + data + '</tbody>');
//$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
I commented out $table.trigger("update", [true]) since if you sort the table on the server before you return it, you shouldn't need to run that, which I'm almost certain is where the bottleneck is.
It is really hard untangle the mess you have but if what you want is ajax requests every 10 seconds it make sense to separate this logic from business logic over data from server.
Your code would also really benefit from using promises. Consider this example
$(document).ready(function() {
var myData = { }
, ajaxPromise = null
setInterval(callServer, 1000)
function callServer() {
ajaxPromise = updateCall()
.then(controlCall)
.done(handler)
.error(errorHandler)
}
function updateCall() {
return $.get('updateTable.php', function(data) {
myData.update = data
})
}
function controlCall( ) {
return $.get('ajaxControl.php', function(data) {
myData.control = data
})
}
function handler() {
console.dir(myData)
}
function errorHandler(err) {
console.log(err)
console.dir(myData)
}
})

$.getJSON request does not run but next line of code does

I have a $.getJSON request that does not run but the line of code right after the request does. If I remove all the code after the $.getJSON request the request will run. How do I get the request to run iterate over returned data then run code following the request.
var eventList = new Array();
$.getJSON('../index.php?/home/events', function(eventItems){
$.each(eventItems, function() {
var event = this;
var eventItem = new Array();
// format the date and append to span
eventItem[0] = formatMDYDate(formatTimeStamp(this.loc_datetime, false), 0);
// add shortdescription to div
eventItem[1] = this.shortdescription;
// check if longdescription exist
if (this.longdescription) {
// create new anchor element for "More Info" link on events
var link = $('<a></a>');
link.attr('href', '../index.php?/home/event_info');
link.addClass('popup');
link.html('More Info');
//link.bind('click', eventPopUp());
link.bind('click', function() {
var addressValue = event.id;
dialog = $('<div></div>').appendTo('body');
dialog.load('../index.php?/home/event_info',
{id: addressValue});
dialog.modal({
opacity: 80
});
return false;
});
eventItem[2] = link;
}
eventList.push(eventItem);
});
});
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
I have no idea what is causing this issue, please help!
Asynchronous means that when you call it the JS runtime will not wait for it to finish before executing next line of code. Typically you need to use call backs in this case.
It's something like:
var a="start";
setTimeout(function(){
a="done";
dosomethingWithA(a);
},1000);
if(a=="done"){}//doesn't matter, a is not "done"
function dosomethingWithA(a){
// a is "done" here
}
In your case the code should look something like:
var eventList = new Array();
$.getJSON('../index.php?/home/events', function(eventItems){
$.each(eventItems, function() {
var event = this;
var eventItem = new Array();
// format the date and append to span
eventItem[0] = formatMDYDate(formatTimeStamp(this.loc_datetime, false), 0);
// add shortdescription to div
eventItem[1] = this.shortdescription;
// check if longdescription exist
if (this.longdescription) {
// create new anchor element for "More Info" link on events
var link = $('<a></a>');
link.attr('href', '../index.php?/home/event_info');
link.addClass('popup');
link.html('More Info');
//link.bind('click', eventPopUp());
link.bind('click', function() {
var addressValue = event.id;
dialog = $('<div></div>').appendTo('body');
dialog.load('../index.php?/home/event_info',
{id: addressValue});
dialog.modal({
opacity: 80
});
return false;
});
eventItem[2] = link;
}
eventList.push(eventItem);
});
processEventList();
});
function processEventList(){
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
}
try
var eventList = new Array();
$.getJSON('../index.php?/home/events', function (eventItems) {
$.each(eventItems, function () {
//....
eventList.push(eventItem);
});
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
});
Alternatively, you can use PubSub with jquery technique
var eventList = new Array();
$.getJSON('../index.php?/home/events', function (eventItems) {
$.each(eventItems, function () {
//....
eventList.push(eventItem);
});
//publisher
$(document).trigger('testEvent', eventList);
});
//subscriber
$(document).bind("testEvent", function (e, eventList) {
if (eventList.length > 0) {
write_Events(eventList);
}
});
For more detials http://www.codeproject.com/Articles/292151/PubSub-with-JQuery-Events
happy coding.. :)
$.getJSON is an asynchronous call. The callback will not execute until after the current function has executed completely. The code after the call will always run BEFORE the getJSON callback runs.
Its possible the write_Events function is throwing an error and stopping execution, which is why the callback is never running. Or it is actually running but you're not seeing evidence of it for whatever reason called by the extra code.
javascript code never wait for the response from the server and we need to stop the processing of javascript until we get the response from the server.
we can do this by using jquery.Deferred
You can also visit this tutorial.

Categories