jquery .load keeps firing javascript after .remove - javascript

I'm making a chat with the simple javascript:
<script>
function chatClick(messages_other_user) {
$('#chatBox').remove();
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
</script>
This function is called in several links with the variable "messages_other_user" changing.
In the file "chat.php" I get the variable of "ou" and I have a script that writes to the console:
if (isset($_GET['ou'])) { $otherUserChat = $_GET['ou']; } else $otherUserChat = 0; // get $otherUserChat
<script>
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
console.log("<?= $otherUserChat ?>");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
But the .remove line doesn't quite get rid of the javascript in the chat.php file. When I click a link to call the javascript chatClick function, it works fine. But when I then click another link that calls chatClick with a different variable for "messages_other_user" the old one keeps firing along with the new one.
How can I destroy the old javascript completely so it doesn't run anymore?

I found the solution - and I was mistaken by the true culprit of the issue.
I thought a console.log would yield the same result as what I truly do - I just chose to replace with console.log in the code for simplicity. So I guess I've learned that's a stupid thing to do.
What is actually happening in the chat.php file in the document ready script is this:
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000);
});
I figured out I didn't readlly need to use the document ready, so I instead, I just do this directly in my script:
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000); // CHECK FOR UNREAD: 1000 equals 1 second
$.ajaxSetup({ cache: false });
For closing the chat window, I now trigger this function:
function closeChat() {
clearInterval(chatUpdateVar);
$('#chatBox').remove();
}
And in the file that calls the above script (chat.php), I check if the function closeChat exists - and if it does, I run it. This is part of the cal to the chat.php:
function chatClick(messages_other_user) {
if (typeof closeChat === "function") {
closeChat();
}
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}

Related

URL check with JS

I have two scripts, first of them clicks on the button and after that browser opens a new window, where i should click on the other button by the second script, is it possible to run them both at the same time, I mean like unite those scripts together?
function run() {
var confirmBtn = document.querySelector(".selector,anotherSelector ");
}
after this new window appears and here`s the second part of my script
var rooms = document.querySelectorAll(" .btn-a-offers");
console.log(rooms);
for (var room = 0; room < rooms.length; room++) {
rooms[room].click();
}
var prices = document.querySelectorAll(" .li-right-side>strong");
console.log(prices);
for (var price = 0; price < price.length; price++) {
}
var prices = [];
document.querySelectorAll(".new-pa-hotelsoffers .li-right-side > strong").forEach(function(price) {
prices.push(parseFloat(price.innerHTML.replace(/[^0-9.]/g, "")))
})
console.log(
Math.min(...prices).toFixed(2)
)
My English is not that good so I want to be sure that I explained everything right, second script must be executed in the new window, that opens after first script
Depending on the logical dependancy of your application and the use of the functions, you could execute the second function in a document.ready function on the second page.
Example:
<script>
//jQuery
$( document ).ready(function() {
secondFunction();
});
//Pure JS
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function() {
secondFunction();
});
</script>
However, if the page is to act independantly, and the second function is only to respond upon the execution of the first function, then that solution would not be the one you are looking for.
In the case where the function has to act entirely dependant on the use of the first function you could parse a value in the URL (better known as a GET variable) and check if that value is set.
Example:
<script>
functionOne() {
window.location.href = '/your_page.php?click=1';
}
</script>
Then on your second page you need to retrieve the GET variable.
<?php
$clicked = $_GET['click'];
?>
You can then perform a check to see if the variable has been set and fire your function upon that logic.
<?php
if($clicked != "") {
echo '
<script>
functionTwo();
</script>';
}
?>
Another way of doing it could be by the use of AJAX and have the other function execute in the AJAX' success function. That way you can eliminate the use of the GET variable, which is visible in the URL.
Example:
<script>
functionOne() {
$.ajax({
type : "POST", //or GET
url : "/your_page.php",
data : {
//parse your POST variable data if any
// variable : value,
// anotherVairable : anotherValue
// [....]
},
success: function (html) {
//Success handling
secondFunction();
}
})
}
</script>
Note that the AJAX used in the example is jQuery AJAX, so if you want to use some AJAX logic involving this structure, you'll need to include a jQuery library.
You should pass some parameter in the URL query like this:
// first-script.js
openNewWindow('http://example.com?run-second-script=1') // openNewWindow is fake function, just for demo
// second-script.js
if (window.location.search.includes('run-second-script=1')) { ... your code here ...}

JavaScript is not applying on page

I have below code that I have written in JavaScript and the script is referenced on the webpage. When the page loads, a call JavaScript happens and the logic's action should be rendered on the webpage.
Right now the script is firing on the webpage, but the action is not getting rendered on the webpage. However, if I execute the script on page console, changes happen.
<script>
function bannerLoad() {
var delayAddOn = setInterval(function() {
if ($(".add-ons").hasClass("current")) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$(".addons-container :last").append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
};
window.onload = function() {
bannerLoad();
};
window.onclick = function() {
bannerLoad();
};
</script>
Can anyone check if there is any issue?
You need to call the script when the page is fully loaded, else the function will be called and can't find the DOM elements.
You should wrap your code inside the ready function:
<script>
//OPEN THE READY FUNCTION
$(function(){
bannerLoad(); //Call of your function when the page is fully loaded
$(window).click(bannerLoad);
});
//CLOSE THE READY FUNCTION
function bannerLoad() {
var delayAddOn = setInterval(function()
{
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
</script>
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page , not just the DOM, is ready.
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
bannerLoad();
$(window).click(bannerLoad);
});
function bannerLoad() {
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
Your script has some little issues. I will try to evaluate them.
As bannerLoad is a function you don't need a ; at the end. Not an issue, just a hint.
As told before, bannerLoad is a function. So why would you wrap the function again in a function for your events? Just pass the function name directly, like window.click = bannerLoad;. Note that there are no bracers at the end, you just pass the name.
You function will always create a new delayAddOn variable with a new interval. So every time you click, another interval will be started and run in background. If you will do it like this, you need to put the variable on the outside of your function, to keep only one interval running at a time.
There is nothing wrong with using onload instead of a ready state from jQuery. But this belongs to you page setup and what you do. It would be more safe to rely on a ready state here, as told by others before. Because you already have a function, you could use it directly by $(bannerLoad);.
var delayAddOn;
function bannerLoad() {
delayAddOn = setInterval(function() {
if ($('.add-ons').hasClass('current')) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$('.addons-container :last').append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
}
$(bannerLoad);
window.onclick = bannerLoad;

How do I move inner HTML script to a seperate Javascript?

So I'm trying to clean up my code and currently the following scripts are in my HTML header
<script type="text/javascript" src="js/mobile.js"></script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});
</script>
I understand that this is quite redundant but I'm a beginner and am still learning. What I'm trying to do is move this code to the mobile/js linked at the very top of the code.
What I have inside the mobile.js right now looks as follows
//initializes each function.
function init() {
hideMenu();
scaleContent();
linkAnim1();
linkAnim2();
linkAnim3();
linkAnim4();
linkAnim5();
}
function hideMenu(){
TriggerClick2 = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
document.getElementById("navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
document.getElementById("navi").animate({width:'0%'}, 1000);
};
});
};
function scaleContent(){
TriggerClick = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
document.getElementsByClassName("content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
document.getElementsByClassName("content").animate({width:'100%'}, 1000);
};
});
};
function linkAnim1(){
document.getElementsByClassName("stayThere").mouseenter(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '-100%'}, 1000);
});
};
//initializes the js functions above
window.onload = init;
sadly the moment I comment it out of the html document it stops doing anything altogether. To explain the functions, the first two are for mobile, bringing in the navigation while resizing the content, the other 5 are for each link Hover to animate a background image.
I'd really appreciate if someone could help me with this as I need it for January 4th, until which my teachers are unavailable.
Thanks again and happy coding
Ok I going to help you the best I can with out doing all of the work for you.
To begin you need only one document ready function for your script.
So take all of the JavaScript Code inside of the document ready functions and place it inside of a single document ready function.
Once you do that link to the JavaScript file by using the script tag right before your closing </body> tag in your html file.
Example(link to external JavaScript File):
<script src="myjavascriptfile.js"></script>
Note: The html code below assumes that your html file is in the same directory as the JavaScript.
Example(External JavaScript File Content):
$(document).ready(function(){//begin document closure
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});//end document closure
Now with that being said there is a lot of things that may be going wrong with your code. Posting your markup(HTML) will help with troubleshooting.
You are using global variables for your TriggerClick2, and TriggerClick one variables. Prefix them using the var keyword and place them at the top of the script inside of the document ready function.
You should try and get in the habit of using === instead of ==. Using === evaluates to exactly equals(matches value and type) where == matches the value. So if you want to make sure your matches the value and the variable type(number and string for example) then use === to prevent any potential headaches in the future.
Example:
var TriggerClick2 = 0;
var TriggerClick = 0;
Keep in mind that variables are scoped at the function level in JavaScript. So any variable that is declared inside of a function can not be accessed outside of the function it is declared in unless it returned by called a function that returns that variables value.

Ajax wont call when output from another ajax

I have comment system using live ajax php, and also include for vote system on that comment
Logic: when i post new comment, system will call ajax function with method post, and display response in above of textarea for comment, that response is include vote system (a class="with_unique_id"), but when i click that vote, it wont calling ajax function (nothing happend in browser console), whereas in current comment that displaying in above of new comment, it working fine.
This is my ajax code for vote
jQuery(document).ready(function($){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "<?php echo base_url('blog/likepost');?>/"+upOrDown[0],
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}else{
$("#likeStatus_"+upOrDown[0]).show();
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Liked';
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
}catch(err) {
alert(err.message);
}
},
error: function(){
alert('Error while request..');
}
});
});
});
It took me a while to read your code, but I guess this is the root cause:
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
This line here:
$("#"+voteId+'_result').html(newValue);
That become the link you want to click again. Right?
If that is so, then you need to re-assign the event handler.
By replacing the DOM element, you have also removed the assigned event handler
PS: You code is very hard to read. It will be nightmare for you to maintain it.
i have fixed my code with adding same ajax code function in response of current ajax with different id.
thankyou

Loading GIF while AJAX completes

This should be quite simple but I'll be darned if I can work it out. Just trying to get a div to display while my ajax is processing and then hide once done (I've put a sleep in there purely to test its working as locally it loads so fast I'm not sure if its working or not)!
The html page has this code in the script: -
$(document).ready(function(){
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
$("#loadingGIF").ajaxStop(function () {
window.setTimeout(partB,5000)
$(this).hide();
});
function partB(){
//just because
}
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
There is then a div in my page like so (which I can see in the source of the page just hidden): -
<div id="loadingGIF" ><img src='${application.contextPath}/images/spinner.gif' height="50" width="50"></div>
The ready code then goes off and calls this: -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for(var i in results){
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
Which references this multiple times calling several AJAX posts: -
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "**Trust me this bits OK ;) **"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
});
}
Any pointers gratefully received...
Interestingly I bunged some alerts into my ajaxstart and stop and neither show up ever so I'm missing something obvious :S When I check the console in firefox I can see that all my POSTs are completing....
You should probably add the Ajaxstart and stop global event handlers to the document node like this
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I realized my problem, I needed to register the ajaxstart and stop to the document not the div!
So instead of this: -
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
I now have: -
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I assume this is because its the document that the ajax is running against not the div although my understanding there may not be 100% accurate at least this works so please tell me if I've misunderstood this! :)
#jbl, thanks for this pointer I did this to also leave the notification on screen for a few more moments just to make sure everything is loaded.

Categories

Resources