So i have a website that I'm doing for a school project. It's supposed to be like PasteBin. So on the right theres a different div (Uued koodid) that shows newest pastes. On click, they are supposed to show what they include using AJAX to refresh the left div. This only works for 4 times and then stops, but URL is still changing. After refresh it changes again and works again for 4 more times.
In main.js i have
...
$.ajaxSetup({ cache: false });
...
$(".uuedKoodid").click(function () {
$(".left-content").load(document.location.hash.substr(1));
});
...
EDIT:
Also other AJAX functions work. If I log in, I can switch between settings and profile perfectly but still cannot watch new codes
When you replace right menu with new code (from ajax call) you don't attach click event again on .uuedKoodid items so they don't do anything. You need to attach event again or attach it like this:
$(document).on('click', '.uuedKoodid', function () {
$(".left-content").load(document.location.hash.substr(1));
});
Edit:
As you noticed this will cause small problem. onclick event run before browser run standard link action. First you load ajax and then browser changes address. This way you are 1 action behind. Better solution than reading with delay (setTimeout) i think would be to read address directly from link:
$(document).on('click', '.uuedKoodid', function () {
var url = $(this).attr('href');
$(".left-content").load(url.substring(url.indexOf("#")+1));
});
Related
I have a table (formatted with Datatables script) and it has a column which contain few icons to manage actions. When user click on an icon, it load a modal and get the modal content using POST method.
Modal has a save button to complete the action after user make their choice. When they click save button, another post script complete the request and feedback to user.
This process working fine when the first time user load the page. There is a refresh button on the page which can reload the TABLE without reload the PAGE.
If user use this button to refresh the page and try above action. it open the modal and Save button trigger the post action 2 times. If the user refresh the page (using the refresh button) again and try one of the action icons, post script run 3 times... in other words if you refresh 10 times post script run 10 times...
if user use the browser refresh button, we don't get this repetition.
Just wondering whether we can fix this without get rid of the refresh button.
We tried different ways to place the script within the page. but still cannot understand what is triggering the multiple post request.
//javascript
//step 1 - load the modal with an action list
$("#proj_data tbody").on("click", ".update_job_progress", function () {
var pn = $(this).attr('mypn');
$.post('reports_job_progress.php', {proj: pn}, function (data) {
$('<div id="progress_update_modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"></div>').appendTo('#modal-container').html(data).modal();
});
});
//step 2 - save user choice
$('body #modal-container').on('click', '.btn_jobaction', function () {
var pn = $("#pn").val();
$.post("reports_job_progress_backend.php", $("#progress_list").serialize(),
function (res) {
if (res === 0) {
alert("There is a problem saving the information. please try again");
} else {
$("#prog" + pn).html(res);
$("#progress_update_modal").modal('hide');
}
}
);
});
//step 3 - destroy the modal
$("body").on("hidden.bs.modal", ".modal", function () {
$("#modal-container").empty();
});
Could you please help me to understand the issue with this code?
It looks like your problem is being caused by binding multiple onclick handlers to the element. Please try using off like this $("#proj_data tbody").off("click").on("click", ... and see if that fixes your issue.
#buffy solution worked. However just adding .off('click') was disabling other icons click event as all icons share the same class. after playing with the code i found adding $(this).off('click') does the trick. Now everything working perfect. Thanks #buffy for providing correct directions.
You will bind the click event multiple times. You could either reset the callback, check if the callback has been set or (much better) set the click listener in a part of your script, that will not be executed, whenever you refresh your page (with the mentioned refresh button) like:
$(document).ready(function() {
$('body #modal-container').on('click', ...
$('body #modal-container').on('click', ...
});
I am new to JavaScript and trying to see why my on event listeners are not working. I have found similar posts on stackoverflow however the solutions are not working for me.
var search = function( event ) {
alert("bobo")
$.get("http://localhost:3000/search", {"search" : $("#Search-Bar").val()}, function(data, status){
if(status == "success")
$(".centering.text-center").html(data)
})
}
var attachListeners = function(){
$("#Search").on("click", search)
$("#SearchIcon").click( () => search() )
$("#Search-Bar").keypress( event => (event.KeyCode == 13 || event.which == 13) ? search() : undefined )
}
$(document).ready( function(){
attachListeners()
})
My website is not a single page application. I have attached the listeners to my navigation search bar where I load a different view through the nav links and my server(ruby back end) uploads a new html page.
On the first load I have noticed that document ready gets called and everything else works. The on and click. After I use my navigation and load a different html page my events disappear. In my html views my searchbar, searchicon, and a search text have consistent id's through out. I have tried using window.load() and putting an onload attribute for my body <body onload=attachListeners()> but neither worked(perhaps I didn't use them properly). I also noticed that when I render the next html views my docment.ready does not get called. However, if I forcefully refresh the page with an F5 the listeners are active again for that one html page. What am I missing here that I don't understand?
It looks like you might be using Turbolinks, from the Readme for the project:
When you follow a link, Turbolinks automatically fetches the page, swaps in its <body>, and merges its <head>, all without incurring the cost of a full page load.
Since this library makes it so the page ever only loads once, normal javascript window.onload, DOMContentLoaded, and jQuery ready events don't function after the initial page load and you have to use
document.addEventListener("turbolinks:load", function() {
instead of those. If you're new to turbo links, I suggest reading through that README to see what it's all about.
I've never understood why the Rails team would put something like this in rails and enable it by default, and in every single project I've made since they made that change the first thing I do is uninstall it, and when I forgot to do so, I spend several hours later in the project wondering why my javascript is broken.
Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}
I'm developing a web based document management for my final year project. The user interacts with only one page and the respective pages will be called using AJAX when the user click the respective tabs (Used tabs for navigation).
Due to multiple user levels (admin, managers, etc.) I've put the javascripts into the correspondent web pages.
When user requests the user request everythings work perfectly except some situations where some functions are triggered multiple times. I found the problem. It is each time the user clicks a tab it loads same scripts as new instance and both of them will be triggered when I call a function.
to load the content I tired
.load and $.ajax(); non of them address the issue.
I tried to put all into the main page at that time my jQueryUI does not work. I tired
$(document).load('click', $('#tab_root li'), function(){});
Same issue remain.
Can anyone help me out this issue?
--Edit--
$(function){
$(document).on('click','#tabs',function(e){
getAjax($(this))
});
}
//method to load via AJAX
function getAjax(lst){
var cont = $(lst).text();
$.ajax({
url:'../MainPageAjaxSupport',
data: {
"cont":cont
},
error: function(request, status, error){
if(status==404){
$('#ajax_body').html("The requested page is not found. Please try again shortly");
}
},
success: function(data){
$('#ajax_body').html(data);
},
});
}
You can't undo JavaScript after it has been executed by simply unloading the file or removing the script element.
The best solution would probably be to set a variable in each JavaScript file you include in your ajax data and include them from an online inline JavaScript inside the ajax data along with a conditional like such:
<script>
if(!tab1Var) $.getScript("filename");
<script>
Older Solutions
You can manually unbind each event before setting them with off.
$(function){
$('#tabs').off('click');
$('#tabs').on('click',function(e){
getAjax($(this));
});
}
Alternatively you can initialize a global variable (eventsBound1=false) for each tab in the main html:
$(function){
if(!eventsBound1){
$('#tabs').on('click', function(e){
getAjax($(this));
});
eventsBound1 = true;
}
}
The tabs click event is only an example you have to do this for each time you bind an event in the scripts that are being reloaded.
if all the events are bound to things inside ajax_body, a final thing you can try is:
success: function(data){
$('#ajax_body').empty();
$('#ajax_body').html(data);
},
You have bind an event click on 'document' so getAjax() only replace the '#ajax_body' not the 'document'.
This means old event is still attached to the 'document' all you need is to unbind event by using $(document).off('click'); or change 'document' to other elements.
I'll admit the title is a bit confusing but it was hard to come up with a better one.
Ok, so What I have is 3 pages, first is the main page that the user loads up and the other 2 are ones that are going to be loaded into the main page with jQuery.
Here is the JavaScript code on the first page:
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php");
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
});
First of all it loads the login form into the page and then it listens for a link to be pressed which will then load up the register form in its place if it is pressed.
The link is in the login form that gets loaded, but unfortunately it doesn't work. What am I doing wrong?
I've tried placing the link on the main page with the JavaScript code and it does work, so is it just the fact that loading the link after the JavaScript has all ready been loaded going to leave it not working?
You need to have a callback function for the first load call. In side that call back is where you would set the click handler for the $('[name=loadRegisterForm]') element. Basically,
you are binding a handler to an element that does not exist until the first load is complete.
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, onLoadComplete);
});
function onLoadComplete()
{
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
}