How to check ajax is completed successfully with jQuery editable plugin - javascript

I am using Jeditable for inline editing.
$(".video_content_right .project_description").editable(BASE_URL+"/update/description", {
indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator.gif'>",
tooltip: "",
type: "textarea",
event: "mouseover",
style: "inherit",
submitdata: function() {
return {
projectidx: $(".my-showcaseowl-carousel .projectidx").eq(currentIndex).val()
}
},
submit: 'Update'
});
Now I want to check if the AJAX request has completed. I have tried with the below, but it is not working:
success: function(data) {}
Any Idea how to check the AJAX request has completed successfully?

You can try to add global ajaxSuccess:
$(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) {
if (ajaxOptions.url == BASE_URL+"/update/description") {
// do some action
}
});

Related

Bootbox dialog.modal('hide') doesn't hide modal

I have a problem with bootbox.js modals. I wanted to use bootbox.dialog for pausing UI while Ajax is being executed and waiting for response. Everything works cool if I use dialog.modal('hide'); inside bootbox.alert with confirm (after clicking OK it hides dialog.modal), but I'd not like to confirm it every time. When I'm using dialog.modal('hide'); outside the bootbox.alert with confirm it doesn't hide dialog.modal... Where is the problem? Working code (hiding modal) is inside success and not working is inside error
var dialog = bootbox.dialog({
message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
closeButton: false
});
var checkboxId = "#" + $(this).attr('id');
var checked = $(this).is(":checked");
if (checked) {
$.ajax({
url: url,
type: "POST",
data: { estimatedCostId: #Model.EstimatedCostID },
success: function (data) {
if (!data.Success)
{
bootbox.alert(data.ErrorMessage, function () {
dialog.modal('hide');
});
$(checkboxId).prop('checked', !checked);
}
},
error: function (request, status, error) {
dialog.modal('hide');
bootbox.alert("Błąd serwera");
$(checkboxId).prop('checked', !checked);
}
});
}
Most likely, this is a timing issue. If your AJAX call is "too quick", the success/fail callbacks are being called before the bootbox.dialog function has resolved. So, this:
dialog.modal('hide');
winds up being called on an undefined object. I was running into a similar issue on a recent project, and solved it by putting the AJAX call into the shown.bs.modal event, like so:
var checkboxId = "#" + $(this).attr('id');
var checked = $(this).is(":checked");
var dialog = bootbox.dialog({
message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
closeButton: false
})
// this is the change
.on('shown.bs.modal', function(){
if (checked) {
$.ajax({
url: url,
type: "POST",
data: { estimatedCostId: #Model.EstimatedCostID },
success: function (data) {
if (!data.Success)
{
bootbox.alert(data.ErrorMessage, function () {
dialog.modal('hide');
});
$(checkboxId).prop('checked', !checked);
}
},
error: function (request, status, error) {
dialog.modal('hide');
bootbox.alert("Błąd serwera");
$(checkboxId).prop('checked', !checked);
}
});
}
});
You can use this also in a simple way
bootbox.hideAll();

How do I rebind jQuery DataTable when the table is auto refreshed by background process

I have a table that I build with data coming from MySQL via PHP code and binding it to DataTable, the table and DataTable work just fine, but I have added a delete button for the table row, when I click that it calls a backend PHP which deletes the record than I am calling a new PHP to query the DB and build a new table and push it back onto the page, all works fine, EXCEPT that when the new query is formatted and pushed onto the age the dataTable is not binding at all, here is my Script.
Thanks
function aa_userDeleteSkill(in_id, in_uid) {
$.ajax( {
url: "user_delete_skill.php",
type: "get", //send it through get method
data: {
id: in_id,
uid: in_uid
},
success: function (response) {
console.log( "success -- delete: " + response );
// cleanup
if ( $.fn.DataTable.isDataTable( '#SkillsUser' ) ) {
$('#SkillsUser').DataTable().destroy();
}
$('#SkillsUser tbody').empty();
// call the rendering function
aa_userSkillRender( in_uid );
jQuery('#SkillsUser').dataTable({
"pageLength": 10,
"ordering": false,
"responsive": true,
"destroy": true,
drawCallback: function(dt) {
//console.log("draw() callback; initializing Select2's.");
//$('.experience-jquerySelect2-tag').select2({tags: true, width: "6em"});
}
});
},
error: function (xhr) {
console.log( "failed -- delete: " + xhr );
}
} );
} // end of fucntion
function aa_userSkillRender( uid ) {
// The following will prevent all future AJAX requests from being cached,
// regardless of which jQuery method you use ($.get, $.ajax, etc.)
$.ajaxSetup({
cache: false
});
// call the backend service
$("#IDuserListSkills").load("./user_render_skill.php?id=" + uid + " #IDuserListSkillsReturned",
function (responseTxt, statusTxt, xhr) {
console.log("responseTxt: " + responseTxt);
if (statusTxt == "success") {
console.log("user_render_skill.php: External content loaded successfully!");
}
if (statusTxt == "error") {
console.log("user_render_skill.php -- Error: " + xhr.status + ": " + xhr.statusText);
}
}
);
} // end of fucntion

jQuery AJAX request TypeError: click is undefinded

I have a jQuery UI Dialog with buttons. The button "OnTMP" should set the state of the element to "on" as long as the button is pressed. The changing of the state is a database update by an AJAX request. I implemented this functionality with mousedown and mouseup. However, when I press the button, everything seems to work fine, but once I release it I get the console output
TypeError: click is undefined jquery-ui.js:10519:5
dialog<._createButtons/http://iis.local/mysite/js/jquery-ui.js:10519:5
jQuery.event.dispatch http://iis.local/mysite/js/jquery-1.11.2.js:4664:15
jQuery.event.add/elemData.handle http://iis.local/mysite/js/jquery-1.11.2.js:4333:6
(I included the debugging jQuery script file, not the minified one)
The widget
$('#pop-up' + id).dialog({
position: { my: "left top", at: "left bottom", of: '#' + id},
close: function () {
$('#pop-up' + id).dialog('destroy');
$('#pop-up' + id).remove();
},
height: 50,
width: 150
});
var buttons = [
{
text: "On",
click: function () {
changeGUIElementState(id, type, "on", false, true);
}
},
{
text: "Off",
click: function () {
changeGUIElementState(bmk, type, "off", false, true);
}
},
{
text: "OnTMP",
mousedown: function () {
changeGUIElementState(bmk, type, "on", true, true);
},
mouseup: function () {
changeGUIElementState(bmk, type, "off", true, true);
}
}
];
$("#pop-up" + id).dialog("option", "buttons", buttons);
The function changeGUIElementState
function changeGUIElementState(id, type, newState, tmp, saveToDB) {
var obj = {};
obj.id = id;
obj.type = type;
var jsonData = JSON.stringify(obj);
console.log("before ajax");
// get all the attributes of the elment from the database
$.ajax({
type: 'POST',
url: '../db/GetElementFromDB.ashx',
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
console.log("ajax done");
response.state = newState;
if (saveToDB) {
notifyDB(id, type, response);
}
// redraw the element
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error in changeGUIElementState()");
console.log(textStatus);
console.log(errorThrown);
});
}
So, the console output when I press and release the button is
before ajax
ajax done
before ajax
TypeError: click is undefined jquery-ui.js:10519:5
ajax done
The element gets redrawn correctly (change of state is change of colour obviously), that's why I didn't look at the console output first.
So any ideas on the issue?
The "click is undefined" message is happening because your "OnTMP" button has no click event handler. jQueryUI requires you to declare a click handler for every button, even if, like in your case, you don't need it. It will assume it is there anyway and try to call it.
To get round it, just add a click handler with an empty function to the definition of the "OnTMP" button:
{
text: "OnTMP",
mousedown: function () {
changeGUIElementState(bmk, type, "on", true, true);
},
mouseup: function () {
changeGUIElementState(bmk, type, "off", true, true);
},
click: function () { } //empty click handler
}

Ajax form in qTip2

I have a table with a list of names, their attributes and comments for each record. I want to be able to display the comments in a tooltip, and also be able to update those comments via Ajax. I would like to show a tooltip or a modal by clicking on a link. This modal will have a textarea with the comments preloaded. The user can modify the comments and submit them to the action page via Ajax. On successful submission the existing tooltip content will also need to be updated.
Any help would be greatly appreciated.
I am using the qtip2 and tipsy plugins.
I am loading the form in the qTip2 tooltip, onclick, through ajax. The link to the form is brought over from the rel tag. Now when I submit the form, it doesn't submit through ajax but directly the action page. This is my JS code:
$('.commentsedit').each(function()
{
// We make use of the .each() loop to gain access to each element via the "this" keyword...
$(this).qtip(
{
content: {
// Set the text to an image HTML string with the correct src URL to the loading image you want to use
text: '<img class="throbber" src="images/throbber.gif" alt="Loading..." />',
ajax: {
url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
},
title: {
text: $(this).attr('title'), // Give the tooltip a title using each elements text
button: true
}
},
position: {
at: 'bottom center', // Position the tooltip above the link
my: 'top right',
viewport: $(window), // Keep the tooltip on-screen at all times
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true // Only show one tooltip at a time
},
hide: 'unfocus',
style: {
classes: 'my_width_setting_class qtip-wiki qtip-light qtip-shadow'
},
events: {
render: function(event, api) {
// Capture the form submission
$('form', this).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':textarea', this);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: 'commentsform.cfm',
data: $(this).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', data.message + ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
});
}
}
})
})
Although an old question, I think that someone will find useful the solution proposed to a similar problem in the qtip2 developer's site and specifically in
http://craigsworks.com/projects/forums/showthread.php?tid=3680
Edit: in response to a comment I reproduce the main part of the answer as a reference:
$('a[class=qTipForm][rel]').each(function(){
var formName = $(this).attr('name');
$(this).qtip({
content: {
//text: '<iframe src="'+$(this).attr('rel')+'" height="400px" width="700px" frameborder="0"></iframe>',
text: 'Loading...',
ajax: {
url: $(this).attr('rel'),
success: function(data) {
// Set the tooltip contents
this.set('content.text', data);
// Bind the form submit event
$('#' + formName).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':input','#' + formName);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: $('#' + formName).attr('action'),
data: $('#' + formName).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
})
}
},
title: {
text: $(this).attr('title'),
button: true
}
},
position: {
my: 'center',
at: 'center', // Position the tooltip above the link
target:$(window),
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true, // Only show one tooltip at a time
modal: true
},
hide: false,
style: {
classes: 'viewTipForm ui-tooltip-rounded ui-tooltip-light',
tip: false
}
})
.click(function(event) { event.preventDefault(); });
})

CkEditor - Template loaded from AJAX

I am using CkEditor and would like to define a custom template, that uses an AJAX function to load a HTML string. I have been able to define custom templates, but if I use a function for the html property of the template object the function is never exectuted. Is it possible to load a template using AJAX with the default template plugin or do I need to write my own?
config.js
CKEDITOR.editorConfig = function (config) {
config.templates_files = ['/pathtomyfile/custom.js'];
};
custom.js (defining my custom templates)
CKEDITOR.addTemplates('default', {
imagesPath: CKEDITOR.getUrl(CKEDITOR.plugins.getPath('templates') + 'templates/images/'),
templates: [
{
title: 'Template 1',
image: 'template1.gif',
description: 'A custom template that does not work',
html: function () {
alert('This alert is never called');
var html = '';
$.ajax({
url: 'MyGetURL',
type: "GET",
async: false,
success: function (result) {
html = result;
},
error: function (jqXhr, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
return html;
}
},
{
title: 'Template 2',
image: 'template2.gif',
description: 'A working custom template',
html: '<h1>I Work!</h1>'
}
]
});
You can't follow this way. The first reason is that editor expects html to be a string, not a function. The second reason is that your AJAX request doesn't make sense since it's called asynchronously and return html is executed before the request is finished.
Anyway, what you want to do is to preload your temple(s) once the editor is ready. You can simply change the following XHR request with a jQuery code but you have to remember that you should call CKEDITOR.addTemplates in success callback:
CKEDITOR.replace( 'editor1', {
templates: 'my',
on: {
instanceReady: function( argument ) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
CKEDITOR.addTemplates( 'my', {
templates: [
{
title: 'My AJAX-driven template',
html: this.responseText
}
]
});
};
httpRequest.open( 'GET', 'yourFile.html' );
httpRequest.send();
}
}
});
If you really wanted to do this live (hard way, I don't recommend it to you), you should overwrite templates command with your code which loads custom templates and then executes the real command. I don't think you need to do this though.
Have fun!
If you're okay with using the bad async: false attribute, I've solved this by changing my custom config file to this:
$.ajax({
type: "POST",
url: '/editor/getTemplates',
async: false,
dataType: "json",
success: function(data) {
CKEDITOR.addTemplates("default",{
imagesPath:CKEDITOR.getUrl(CKEDITOR.plugins.getPath("templates")+
"templates/images/"),
templates:data});
},
error: function() {
alert("Error!");
}
});
Where the server loops through all templates and generates a json encoded array as templates should be.
If you don't set async to false (since it's depercated in newer jQuery), the problem will be that the editor will try to access the array before it arrived, In that case I think you'd have to edit internal files.

Categories