jquerymobile. double execute function - javascript

I have such code:
function getData(){
$.ajax({
url: 'http://pechati.ru/extdata/baseparts/filialsWSunsec.php',
contentType: "application/x-www-form-urlencoded;charset=utf8",
dataType: 'json',
success: function(jsonData){
//alert('Load was performed.');
console.debug('Data received.');
//jsonData = win2unicode(jsonData);
console.debug(jsonData);
$.each(jsonData,function (filial,dataFilial) {
//
//console.debug(filial);
var option = '<option value="'+filial+'" data-phone="'+ dataFilial.phone+ '" data-email="' + dataFilial.email + '"> ' + filial + '</option>';
//filial active
var activeFilial = 0;
if (parseInt(dataFilial.mainList)>0){
activeFilial++;
}
if (parseInt(dataFilial.contacts)>0){
activeFilial++;
}
if (parseInt(dataFilial.uslugi)>0){
activeFilial++;
}
if (activeFilial>0){
$('#filial-name').append(option);
}
});
},
error: function(error){
console.debug('We have a problem: ');
}
});
}
...
$(document).bind('pageinit', function() {
$('a.get-order').on('click', function () {
getData();
});
}
getData is executing twice after click on a.get-order it. Why is happening it?
This is element placed in :
<div id="one">
...
</div>
<div id="two">
...
<a class="get-order">...</a>
</div>
The first page is loaded "#one". From it called page "#two". After click on a.get-order I have double execution getData(). If I am calling page "#three" from page "#two" and execute some function there it executed three times.
Why is it happening and how fix it?

Your code:
$(document).bind('pageinit', function() {
$('a.get-order').on('click', function () {
getData();
});
}
Runs every time any page is initialized. So the click handler is added once when #one is initialized and then again when #two is initialized. Change it to
$(document).on("pageinit","#two", function(){
$('a.get-order').on('click', function () {
getData();
});
});
This way the click handler is only added once when page #two is initialized.

Related

jQuery script re-starting on ajax call

I'm building a javascript widget which updates a div with html from an external domain. It also intercepts any link clicks in this div and fetches fresh data, updating the div.
Issue I'm having is that when the link callback function runs after a click the JS script is re-run in it's entirety from init().
In trying to debug it, in handleClick() if I hard-code the url the script runs once as expected e.g. url: '/page-3/', but if I access the href from the clicked link e.g. url: jQuery.attr('href') the script re-runs. Is there any way of accessing this attribute without the script starting anew?
"use strict";
(function () {
var jQuery; //noconflict reference to jquery
var serverFQDN = 'http://127.0.0.1:8000';
var container = '#my-container';
function init() {
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.4.1') {
...
}
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict();
console.log('jQuery is now loaded');
main();
}
function main() {
jQuery(document).ready(function () {
jQuery('head').append('<link href="' + serverFQDN + '/static/css/cleanslate.css" rel="stylesheet" type="text/css">');
jQuery('head').append('<link href="' + serverFQDN + '/widget.css" rel="stylesheet" type="text/css">');
jQuery(container).addClass('cleanslate');
// build the initial widget
jQuery.ajax({
method: "GET",
cache: false,
url: "/page-1/",
success: function (response) {
jQuery(container).html(response);
// handle clicks
jQuery(container + ' a').click(handleClick);
}
});
});
}
function handleClick() {
console.log('Intercepted link click');
jQuery.ajax({
method: "GET",
cache: false,
url: jQuery.attr('href'),
success: function (response) {
console.log('succesfully loaded external html');
jQuery(container).html(response);
jQuery(container + ' a').click(handleClick);
}
});
// disable default click action
return false;
}
init();
})();
To access the href attribute you can use the event argument, provided by the Jquery click callback:
function handleClick(event) {
//you probably want this
event.preventDefault();
console.log('Intercepted link click');
jQuery.ajax({
method: "GET",
cache: false,
url: jQuery(event.target).attr('href'),
success: function (response) {
console.log('succesfully loaded external html');
jQuery(container).html(response);
jQuery(container + ' a').click(handleClick);
}
});
// disable default click action
return false;
}

Bootstrap 4 Modal only runs once

So for some reason, I created two modals. However, when I open either of them the first time, and then close the modal it will no longer open either of the two when I do t he action that worked the first time.
here is my javascript:
<script>
$(document).ready(function()
{
$("#accountsTable").tablesorter();
$('#newAccount').on('click', function() {
$.ajax({
async:true,
url: '/crm/accounts/create_account_modal',
success: function(res)
{
$('.createAccountModalBody');
alert(res);
$('#createAccountModal').modal({show:true});
$('.createAccountModalBody').html(res);
}});
});
$('tr').on('dblclick', function() {
var AccountID = $(this).find('td').first().html();
alert(AccountID);
$('.editAccountModalBody').load('/crm/accounts/edit_account/1');
$('#editAccountModal').modal('show');
});
$('#editAccountModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$(this).empty();
$(this).removeAttr('style');
});
$('#createAccountModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$(this).empty();
$(this).removeAttr('style');
});
});
$('tr').on('dblclick', function() {
var AccountID = $(this).find('td').first().html();
alert(AccountID);
$('.editAccountModalBody').load('/crm/accounts/create_account_modal');
$('#editAccountModal').modal('show');
});
</script>
with
$(this).empty();
you are removing all the html inside the modal, so you'll not have the html displayed on the next click
I suggest to append the data on a particular id / class name and just empty that id and not the whole modal
like:
$("#editAccountModalDATA").empty();

How to display a random quote as soon as page loads?

I am working on a random quote app. Quote is display when click a new quote button but I want quote already display when page loads. I invoked a function but it still does not work. Thank you!
Here is my code:
$(document).ready(function() {
function randomQuote() {
$('#get-quote').on('click', function(e){
e.preventDefault();
// Using jQuery
$.ajax( {
url: "http://quotes.stormconsultancy.co.uk/random.json",
dataType: "jsonp",
type: 'GET',
success: function(json) {
// do something with data
console.log(json);
data = json[0];
$('#quotation').html('"'+json.quote+'"');
$('#author').html('-- '+json.author+' --');
$('a.twitter-share-button').attr('data-text',json.quote);
},
});
});
$('#share-quote').on('click', function() {
var tweetQuote=$('#quotation').html();
var tweetAuthor=$('#author').html();
var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
window.open(url)
});
}
randomQuote();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try removing click listener. inside randomeQuote() remove click listener.
keep your click listener out side of document.ready
$(document).ready(function() {
randomQuote(); // call initially and get random quote
});
function randomQuote() {
$.ajax( {
url: "https://quotes.stormconsultancy.co.uk/random.json",
dataType: "jsonp",
type: 'GET',
success: function(json) {
// do something with data
data = json[0];
$('#quotation').html('"'+json.quote+'"');
$('#author').html('-- '+json.author+' --');
$('a.twitter-share-button').attr('data-text',json.quote);
},
});
$('#share-quote').on('click', function() {
var tweetQuote=$('#quotation').html();
var tweetAuthor=$('#author').html();
var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
window.open(url)
});
}
$('#get-quote').on('click', function(e){
e.preventDefault();
randomQuote();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get-quote">get quote</button>
<div id="quotation"></div>
Remove the onClick listeners so that when you call the function it will update directly.
function randomQuote() {
$.ajax( {
...
success: function(json) {
... //do updates
},
});
}

div should be refreshed every three seconds using jquery and ajax

below is my script in that, particular div should be refresh every three seconds. how to add the time interval in my code using jquery and ajax?
<script>
$(document).ready(function () {
$('#data_form').on('submit', function (e) {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div></div>');
$('#messagee').val('');
},
error: function ()
{
alert('failed');
}
});
e.preventDefault();
});
scrollDown();
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 200);
}
});
</script>
To refresh the div every 3Sec.
You can use "setInterval" function.
And to stop this interval you can use "clearInterval" function.
The simple code is as follows:
var refreshIntervalId = setInterval(function(){
// alert("Hello");
//Your Div's ID
}, 3000);
/* later */
clearInterval(refreshIntervalId);
This code simply calls the alert every 3seconds,so modify the above code and put the div's id to be refreshed.
You can use setInterval javascript function for that. check the code snippet below
setInterval(scrollDown, 3000);
I hope this will help you. Please check below code.
function animatedText() {
$('.text').animate({ opacity: 1 }, 200, function() {
$('.text').animate({ opacity: 0 }, 200);
});
setTimeout(function() {
animatedText();
},3000);
}
animatedText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Animated Text</div>
Use
setInterval(function(){
getMessage();
}, 3000);
setIterval lets you to repeat a function or a code block every n seconds.
I think you should add your ajax call into a function.
function getMessage () {
//Your ajax call here
}
This way the code could be reused more times without repeating it.

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

Categories

Resources