Ajax form in qTip2 - javascript

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(); });
})

Related

Click event listener on elements with the class stops working after first click

I have an anchor element with a class called .trigger. I have a listener for that class which opens a modal using the iziModal framework. On first click the function works as expected. On second click the listener does not work. Instead i get in console "$(...).iziModal is not a function". What am i doing wrong? Any help would be greatly appreciated. I am bot of a newbie with JS.
** Jquery ver **
3.6.3
Ajax Example 8
$(document).on('click', '.trigger', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var wtitle = $(this).data('title');
$('#my-modal').iziModal({
title: wtitle,
bodyOverflow: true,
width: 600,
headerColor: '#000',
fullscreen: false,
openFullscreen: false,
transitionIn: 'fadeInDown',
transitionOut: 'fadeOutUp',
onOpening: function(modal) {
modal.startLoading();
$.ajax({
url: url,
type: 'GET',
success: function(data) {
modal.stopLoading();
modal.setContent(data);
},
error: function() {
alert('Error loading content.');
}
});
}
});
$('#my-modal').iziModal('open');
});
I have tried initialising the izi modal outside of the trigger event (suggested by ChatGPT).
I think this would work but I am not sure how to pass the URL from the onClick event to $('#my-modal').iziModal(). If someone could suggest that then i could try.
// Initialize the iziModal
$('#my-modal').iziModal({
title: '',
bodyOverflow: true,
width: 600,
headerColor: '#000',
fullscreen: false,
openFullscreen: false,
transitionIn: 'fadeInDown',
transitionOut: 'fadeOutUp',
onOpening: function(modal) {
modal.startLoading();
$.ajax({
url: '',
type: 'GET',
success: function(data) {
modal.stopLoading();
modal.setContent(data);
},
error: function() {
alert('Error loading content.');
}
});
}
});
// Bind the click event to the trigger element
$(document).on('click', '.trigger', function(event) {
event.preventDefault();
event.stopPropagation();
var url = $(this).attr('href');
var wtitle = $(this).data('title');
// Set the modal title
$('#my-modal').iziModal('setTitle', wtitle);
// Set the modal content
$('#my-modal').iziModal('setContent', '');
$('#my-modal').iziModal('startLoading');
$.ajax({
url: url,
type: 'GET',
success: function(data) {
$('#my-modal').iziModal('stopLoading');
$('#my-modal').iziModal('setContent', data);
},
error: function() {
$('#my-modal').iziModal('stopLoading');
alert('Error loading content.');
}
});
// Open the modal
$('#my-modal').iziModal('open');
});

How do I use the Bootstrap toggle to create an event of true and false on my form?

For example, when I (administrator) create a record and leave the Bootstrap toggle on, the record will be visible to the users. However, if I create a record and make the Bootstrap toggle off the record will be invisible to the users.
<script>
//Using a function technique to create a JavaScript class, WebFormData
function WebFormData(inSessionSynopsisName, inIsVisible) {
this.sessionSynopsisName = inSessionSynopsisName;
this.isVisible = inIsVisible;
}
$('#toggle-event').change(function () {
var collectedIsVisible = $('#isVisibleInput').val();
})
$('#saveButton').on('click', function () {
var collectedSessionSynopsisName = $('#sessionSynopsisNameInput').val();
var webFormData = new WebFormData(collectedSessionSynopsisName, collectedIsVisible);
var webFormDataInString = JSON.stringify(webFormData);
$saveSessionSynopsisHandler = jQuery.ajax({
type: 'POST',
url: '/API/SessionSynopses/',
dataType: 'json',
contentType: 'application/json;',
data: "'" + webFormDataInString + "'"
})//end of ajax() call
$saveSessionSynopsisHandler.done(function (data, textStatus, jqXHR) {
new Noty({
text: data.message, type: 'success',
layout: 'center',
template: '<div class="noty_message"><span class="noty_text"></span>'
}).show();
});//end of saveCourseHandler.done();
$saveSessionSynopsisHandler.fail(function (data, textStatus, jqXHR) {
console.log(textStatus);
console.log(data);
console.log(jqXHR);
new Noty({
text: data.responseJSON.message, type: 'error',
layout: 'center',
template: '<div class="noty_message"><span class="noty_text"></span>'
}).show();
});//end of $saveCourseHandler.fail();
});//end of $('#saveButton').on('click', function () {
</script>
check befor onload your page the user:
if user admin change style to your button to turn it on
else if user not admin change style to your button to turn it off
to do some processing before loading a page you can use onunload please read this https://www.w3schools.com/jsref/event_onunload.asp

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
}

How to check ajax is completed successfully with jQuery editable plugin

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
}
});

Insert HTML using jQuery

I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});

Categories