Tooltip script. Need to correct code - javascript

$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
var ajaxQueue = $({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
});
});
it's my first experience with js and i need some help. for tooltips i use bootstrap tooltips.
when cursor hover on link, script send post data to controller and receive callback data. in the first hover script receives the data, but tooltip doesn't pop up, only the second hover. how i can fix it?
and one more question. can script will send the request only the first mouse hover, and the following hover will use the information from the cache?
and sorry my english ;D

It is hard to test cross domain
Here is what I THINK you need
$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
$.ajax({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
});
});

Create flag for ajax query.
var isTooltipTextEmpty = true;
$('.challenge').mouseover(function(){
if(isTooltipTextEmpty) {
...add ajax query here)
}
}
And you need to trigger tooltip show event, when ajax query is ready like this
.success(data) {
$('.challenge').show();
isTooltipTextEmpty = false; //prevents multiple ajax queries
}
See more here: Bootstrap Tooltip

Related

How can I fill all data in select2 (4.0) when page loaded?

I am using select2 plugin (v.4.0).
What I am trying to do:
$("#search-input-chains").select2({
placeholder: "Unit",
theme: "bootstrap4",
allowClear: true,
initSelection: function (element, callback) {
callback({id: 1, text: 'Text'});
},
ajax: {
url: function () {
return getURLForFilial();
},
dataType: 'json',
delay: 250,
processResults: function (response) {
console.log(response);
return {
results: response
};
},
cache: false
}
});
function getURLForFilial() {
return '/user/rest/data/entry/units/branches?type=1';
}
I need to understand, whether my control has data retrieved from DB or not, and if there is no data - this select list shall not be activated.
I found how I can understand the data amount:
$("#search-input-chains").data().select2.results.$results[0].childNodes.length
(maybe there is another way that is much better?)
But this piece of code returns 0 until I will activate (click) on the select2 box and trigger AJAX request to find data.
I read a lot about how can I perform the pre-call off AJAX, but it doesn't work.
I tried to trigger event on select2 in such a way:
$("#search-input-chains").val().trigger('change');
Please, advice, how can I load data to my select2 control with the page load to understand whether I need to disable this select or not?
I've made it via AJAX:
ajax({
type: 'GET',
url: '/user/rest/data/entry/units/branches?type=1'
}).then(function (data) {
if (data.length !== 0) {
chainsSelectElement.prop("disabled", false);
chainSelectorHasData = true;
} else {
// create the option and append to Select2
let option = new Option('Nothing', 'null', true, true);
chainsSelectElement.append(option);
chainSelectorHasData = false;
chainsSelectElement.prop("disabled", true);
}
getDataForSubdivisions();
});

How can I ajax only html table rows instead of sending the entire form inputs?

I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});

Dynamic content not shown after Ajax

This question is related to this one.
I'm using Tooltipster JQuery plugin to show tooltips on my website like:
HTML
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
JS
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, basically I load via Ajax new content with a function:
function exploreTracks(start, filter) {
$('#load-more').html('<div class="load_more" style="height: 232px;"><div class="preloader-loadmore preloader-center"></div></div>');
if(filter == '') {
q = '';
} else {
q = '&filter='+filter;
}
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_explore.php",
data: "start="+start+q+"&token_id="+token_id,
cache: false,
success: function(html) {
$('#load-more').remove();
// Append the new comment to the div id
$('#main-content').append(html);
// Reload the timeago plugin
jQuery("div.timeago").timeago();
// Update the Track Information
updateTrackInfo(nowPlaying);
}
});
}
New contents on mouse hover don't show any tooltip, from console I can't see any error or warning and on network load_profilecard.php is not called.
I have placed the script (same JS as above) directly on my content page, so why the tooltip is not shown on mouse hover?
My solution
As suggested in comments by Evan I used delegation option for this purpose.
$(function() {
$('body').on('mouseenter', '.tooltip:not(.tooltipstered)', function(){
$(this)
.tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250 })
.tooltipster('open');
});
});

Javascript used for random button

I am a beginner in JavaScript means and programming, and I encountered a problem for a personal project. I made an anime fight website getting some information from MySQL Database each anime has ten videos and photos, through a random button it randomly takes one link for a video and photo. The problem is that it only work only one time if I random again nothing happens. I know that in order to make that work I have to rewrite the code again after the success of the first random for getting a second random but this will create an infinite loop. Can somebody help me solve this issue.
This is the code used:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
$('#random').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
})
}
});
})
});
</script>
I understand that $.ajax request overwrites initial .imgResponsive element, am I right? Along with overwritten .imgResponsive you permanently lose click event attached to this element.
In that case you need to attach event to element container, eg.
$(document).on('click', '.imgResponsive', function() {....
...
}
instead of
$('.imgResponsive').click(function(){ ....
You have to register EventListener in order to proceed.
Try this:
<script>
var showImage = function(e){
e.preventDefault();
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
};
$(document).ready(function () {
$('document').on('click', '.imgResponsive', showImage);
$('document').on('click','#random', showImage);
});
</script>
The way your code is written, you're handling only a single AJAX response (aside from the first one) with no way to handle more AJAX requests triggered by clicking the #random button. You need to write functions for handling button clicks and the AJAX responses instead of using anonymous functions; that way it's modular enough that you can listen for and handle more button clicks in the future.
Something like this:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
$('#random').click(handleButtonClick);
});
function handleButtonClick(e){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
}
function handleResponse(response){
$('#hiddenPage').html(response);
}
});
</script>
Edit: Another thing that might be happening is that your #random element is being overwritten every time you do $('#hiddenPage').html(response);. In that case you would need to attach a new event handler to the new #random element every time you handle an AJAX response:
function handleResponse(response){
$('#hiddenPage').html(response);
$('#random').click(handleButtonClick);
}

How to finish loading condition that a function to execute another function in jquery?

I have the following script to add a new value to the array of my session variable, and show me the varible totally live session
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
});
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (data) {
session = data;
alert(session);
});
});
}}
})( jQuery );
the problem is that the POST shipping takes longer than the call GET ALERT then shows me the session variable not updated.
Is there a way to put an IF condition for shipping only when POST is complete return the response I GET?
thanks
Actually, what you want do do is to use a callback - that is, a function that is called as soon as your POST ajax request returns.
Example:
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
})
.done(
//this is the callback function, which will run when your POST request returns
function(postData){
//Make sure to test validity of the postData here before issuing the GET request
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (getData) {
session = getData;
alert(session);
});
}
);
});
}}
})( jQuery );
Update per Ian's good suggestion I've replaced the deprecated success() function with new done() syntax
Update2 I've incorporated another great suggestion from radi8

Categories

Resources