I am trying to display loading message before sending ajax request, and on success callback, hide the message again.
$('#uploadForm').submit( function () {
var fileExists;
if((typeof reference !== 'undefined') && reference) {
$('#loading').css('display', 'block');
CheckFileExists(reference).success(function(response) {
if(response.status === 'true')
fileExists = true;
else if(response.status === 'false')
fileExists = false;
$('#loading').css('display', 'none');
});
if(fileExists) {
alert('Sorry, file already exists!');
return false;
}
}
return true;
});
function CheckFileExists(el)
{
var fi = el; // GET THE FILE INPUT.
if(fi.value !== "") {
var file_name = fi.files[0].name; // FILE NAME
return $.ajax ({
url: "task/file-check",
data: { file_name : file_name},
method: 'POST',
dataType: 'json',
async: false
});
}
}
But this will make the ajax request first, alert pops up, and finally the message appears.
I also tried keeping the if-else inside setTimeout:
$('#uploadForm').submit( function () {
var fileExists;
// load
appendData();
setTimeout(function() {
if((typeof reference !== 'undefined') && reference) {
CheckFileExists(reference).success(function(response) {
if(response.status === 'true')
fileExists = true;
else if(response.status === 'false')
fileExists = false;
$('#overlay-procurement').remove();
});
if(fileExists) {
alert('Sorry, file already exists!');
return false;
}
}
return true;
}, 3000);
});
This will also submit the page (page reloads) while the ajax request is also being made (loader appears and alert pops up).
Also tried beforeSend but found out it doesn't work with async: false.
Do it after submit
$('#uploadForm').submit( function () {
$('#loading').css('display', 'block');
and on success
$('#loading').css('display', 'none');
Related
I'm using ajax to update some info in my page. I used the $.when $.then functions to identify when the call is over and should activate the timer.
The issue here is that when the call gets a "Failed to load resources" error (no matter which one of them), it will simply stop working at the middle of the execution, and without resetting the timer.
This is the code:
function UpdateCODGW()
{
if(CODGW_Running == false && session_ended == false)
{
CODGW_Running = true;
$.when($.ajax({
url: 'THE_URL',
data: {ajax: 'gwonline'},
type: 'post',
dataType:'json',
success: function(sInfo) {
if(sInfo.session !== false)
{
session_id = sInfo.session;
var gwstatus = $(CODGWID);
sInfo.isonline ? CODGW_Offline = 0 : ++CODGW_Offline;
if(!sInfo.error && sInfo.isonlinestr !== CODGW_Old && (sInfo.isonline || CODGW_Offline >= 3))
{
gwstatus.html(sInfo.isonlinestr);
CODGW_Old = sInfo.isonlinestr;
}
}
else
session_ended = true;
},
failure: function() {
}
})).then(function() { if(session_ended == false) { CODGW_Running = false; UpdateCODGWTimer(); } });
}
}
I don't know what I did wrong that the code won't handle such errors.
I am having issued chaining a bunch of deferred 'then's in my javascript function.
In JQuery 1.7.2 I was able to create something like the following example, passing parameters from each one to determine if I continue.
myAjaxFunction(myParametersObject)
.done(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// final code here
}
});
It works perfectly on JQuery 1.7.2 but I am working on a project that requires JQuery 1.11.1 and this no longer works.
How can I pass parameters to the upcoming 'then' in JQuery 1.11.1?
Return jQuery promise value from myAjaxFunction appear to be defined as noErrors at done handler argument parameter
.done(function (noErrors) {
within .done handler as anyErrors ?
if (anyErrors == true) {
similarly at
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
?
Try setting same parameter as argument parameter and within handler , .e.g. anyErrors
var dfd = $.Deferred().resolve(true);
dfd.done(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// final code here
document.body.textContent = anyErrors;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
jsfiddle http://jsfiddle.net/zr5rzb7v/1/
You could use it if you use first then and then done:
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
See official jquery api documentation: http://api.jquery.com/deferred.then/#deferred-then-doneFilter-failFilter-progressFilter
I've wrote following code for searching via ajax. When key up fired, an ajax request is made after 500ms. But the searching animation doesn't stop (hide() method).
$('#mainsearch .searchinput').keyup(function(e) {
if (e.which !== 0) {
var searchval = $(this).val().trim();
if(aSearch[searchval]) {
$('#mainsearch #sugbox #sugres').html(aSearch[searchval]);
}else if(prevs !== searchval) {
prevs = searchval;
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(function() {search(searchval)}, 500);
$(this).data('timer', wait);
}
}
});
function search(searchval) {
console.log("searching for "+searchval)
if(lastrequest && lastrequest.readystate != 4){ // abort past requests
lastrequest.abort();
lastrequest = null;
delete lastrequest;
$('#mainsearch #finding').hide();
}
if(searchval != "") { // make an ajax call
lastrequest = $.ajax({
url:"/ajaxsearch.php?key_word="+searchval,
type: "GET",
dataType:'json',
cache:true,
beforeSend:function() {
$('#mainsearch #finding').delay(400).show(0);
},
complete: function(jqXHR, status){
console.log('complete');
$('#mainsearch #finding').hide();
},
success:function(result){
$('#mainsearch #finding').hide();
if(result.length > 0 ) {
var outp = searchParse(result);
$('#mainsearch #sugbox #sugres').html(outp);
aSearch[searchval] = outp;
} else
$('#mainsearch #sugbox #sugres').html('<li> Not Found </span></li>');
$('#mainsearch #finding').hide();
},
error : function (xhr, ajaxOptions, thrownError) {
$('#mainsearch #finding').hide();
}
});
}
}
I get desired results in search with no error. but the hide() isn't hiding the animation. However, entering $('#mainsearch #finding').hide(); hides the animation.
Note : Here #mainsearch #finding is a div which is animated by css3.
Take away the delay i think ajax returns faster than delay...
$('#mainsearch #finding').delay(400).show(0);
$('#mainsearch #finding').show(0);
I'm not able to reload dynatree after I received response for AJAX request.
I've a pulldown 'plan.viewType' in code below. I'm invoking a JS function upon a new value selected in this pulldown which will in turn call an AJAX function.
<form:select path="plan.viewType" id="viewType" style="width:11.6em" onChange="loadView()" multiple="false">
<form:options items="${plan.viewType}"/>
</form:select>
I've two trees - dim_tree and kpi_tree.
$(document).ready(function(){
$.fn.clearable = function (treeid) {
var $this = this;
$this.wrap('<div class="clear-holder" />');
var helper = $('<span class="clear-helper">x</span>');
$this.parent().append(helper);
helper.click(function(){
$this.val("");
$('#' + treeid).dynatree('getRoot').search("");
});
};
$("#dimsearch").clearable("dim_tree");
$("#kpisearch").clearable("kpi_tree");
$("#dim_tree").dynatree({
checkbox: true,
selectMode: 3,
children: (isEdit == "true")? eval('('+'${plan_dimension_edit_info}'+')') : eval('('+'${plan_dimension_info}'+')'),
dnd: {
onDragStart: function (node) {
return false;
},
onDragStop: function (node) {
return false;
},
onDragOver: function (targetNode, sourceNode, hitMode) {
return false;
},
onDrop: function (targetNode, sourceNode, hitMode, ui, draggable) {
return false;
}
},
onSelect: function(select, node) {
if(select && dimKPIMisMatch(node)) {
node.select(false);
//showToolTip(node.span, dimMsg);
return;
}
createTreeSortable(select, node, "DIM");
}
});
$("#kpi_tree").dynatree({
checkbox: true,
selectMode: 3,
children: (isEdit == "true")? eval('('+'${plan_measurement_edit_info}'+')') : eval('('+'${plan_measurement_info}'+')'),
dnd: {
onDragStart: function (node) {
return false;
},
onDragStop: function (node) {
return false;
},
onDragOver: function (targetNode, sourceNode, hitMode) {
return false;
},
onDrop: function (targetNode, sourceNode, hitMode, ui, draggable) {
return false;
}
},
onSelect: function(select, node) {
if(select && kpiDIMMisMatch(node)) {
node.select(false);
//showToolTip(node.span, kpiMsg);
return;
}
createTreeSortable(select, node, "KPI");
}
});
});
I would like to reload these two trees when I get response from AJAX call below.
var loadView = function() {
if($("#viewType").val() == "Default View") {
$.ajax({
url : "planmntsdefault.do",
type : "GET",
success : function (data) {
var node = $("#dim_tree").dynatree("getTree").getRoot();
if(node && node.isLazy())
{
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
else
{
node.activate();
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
node = $("#kpi_tree").dynatree("getTree").getRoot();
if(node && node.isLazy())
{
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
else
{
node.activate();
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
},
error : function ( xhr, textStatus, error ) {
}
});
}
}
I referred to other posts how to reload/refresh/reinit DynaTree? which didn't resolve the problem. I've tried another variation where I do destroy and reload. Neither of these approaches work. Am I missing something here? Thanks.
You could try this:
success : function (data) {
$("#dim_tree").dynatree("getTree").reload();
$("#kpi_tree").dynatree("getTree").reload();
},
you can solve your problem by three method if you want to add new data and response come by ajax then u can add following code in dynatree
jQuery
$.ajax({
url : "planmntsdefault.do",
type : "GET",
success : function (data) {
var node = $("#dim_tree").dynatree("getTree").getRoot();
/*here you can use i assume title
come (by this name of root is set in
dynatree and if set isFolder :true then
folder icon appear in dyna tree*/
var childNode = node.addChild({ title: data.title,
isFolder: true
});
}
})
and if u want to edit some root name then you can use
In Previous Code Where We Use Add Set Below Line
var node = $("#tree").dynatree("getActiveNode");
node.data.title = $newtitle;
And For Delete
var node = $("#tree").dynatree("getActiveNode");
activeNode.remove();
these all steps when we apply then it look that dyna tree referesh hope it make help
I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.
Cheers!
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
}
},
}).always(function () {
setTimeout(checkBookStatus, 8000);
});
};
checkBookStatus();
});
t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.
use clearTimeout
e.g. you defined :
id = setTimeout(checkBookStatus, 8000);
then you can remove this function by :
clearTimeout(id)
Before your call of checkBookStatus() at the end, put another call: var interval = setInterval(checkBookStatus, 8000);. Then on success you can clearInterval(interval).
Do not use setTimeout for iteration.
A lot of answers are suggesting just to use clearTimeout() however, you are checking the status after the timeout has expired, there is no timeout to clear. You need to not call setTimeout() in your always() function rather than to clear anything. So you could re-inspect the status inside your always() function I suppose, but your data object isn't in scope there. It would be preferable to just use setInterval() outside of your checkBookStatus() function.
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
clearInterval(interval);
}
}
});
};
var interval = setInterval(checkBookStatus, 8000);
checkBookStatus();
});
Call clearTimeout with the value previously returned by setTimeout. This would give you something like:
$(function() {
var timeoutID;
var checkBookStatus = function () {
[…]
else if (data.status == "#{Job.success}") {
clearTimeout(timeoutID);
[…]
}).always(function () {
timeoutID = setTimeout(checkBookStatus, 8000);
[…]
When you use setTimeout, use like this:
var myTime = setTimeout(checkBookStatus, 8000);
to clear it just:
clearTimeout(myTime);
the following should work...
the setTimeout function return an instance of the setTimeout function. Keep this value in a variable and pass it to the function clearTimeout when you want to prevent the event from firing again.
i.e.
var t = setTimeout(1000, someFunction);
...
//after you no longer need the timeout to fire, call
clearTimeout(t);