Load scripts in bootstrap modal when getting fragment of page - javascript

I'm currently getting a fragment of a page and loading in bootstrap modal.
This fragment of page includes the jQuery required to load Google Maps but when the modal loads the content, all scripts are getting stripped so subsequently, the maps don't load.
Even if I directly insert the scripts inside the modal-body class, they still get stripped.
Is there a workaround to this at all?
What we're currently using to trigger the modal is:-
Launch demo modal
I can provide further code in use if needed to answer accurately.
=== Edit: Providing more code in use on request...
So we're including a sitewide link that triggers bootstrap modal. The link that is triggering modal can be seen above and here is the rest of the code in relation the modal.
What we wish to load in the modal is just a fragment of the page at /stores, all the code that is loaded at this URL can be seen here. From this page though, we only really wish to load everything inside .modal-container on line 192 but as necessary scripts reside outside of this div in the same file, we aren't capturing this when we try to load in modal. So previously, our modal trigger looked like:-
Launch demo modal
This then led us to try and just wrap entire file content inside div and call it's contents as the fragment of page in modal so that we can pull the necessary scripts required to load #map_canvas but alas, all scripts are stripped out of modal...
Hope this gives greater explanation into what we're trying to achieve.
=== Edit 2: We've actually fixed this via a workaround but it was a mammoth job so will post answer as soon as I can...

I'm using the following code to load view on boostrap modal :
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$(url).modal('open');
} else {
$.get(url, function(data) {
$(data).modal();
}).success(function() { $('input:text:visible:first').focus(); });
}
});
With the following trigger :
<i class="icon-plus icon-white"></i>
By using this method you will ensure that all you script will be loaded when your modal will display. This is only this workaroung that I found to correctly showing my modal.
Everything that I have to show on my form (new.html) will be displayed perfectly.
Thus, I suggest that you put all you releavant code to Google Map on the page corresponding to /stores.
Edit
You trigger should be :
Launch demo modal
Instead of :
Launch demo modal`
Edit2
The problem that I see, is that you modal inclusion do not get the JS files because these are not within your inclusion section. I'm not a PHP expert, but here is to option that you might try :
Option1 (not very clean)
You can add <script>Google Map required JS File</script> tag inside the <div class="modal-container"></div> but you will get duplicate tag for the same JS file.
Option2 (Might be possible ?)
Create new file and add your section <div class="modal-container"></div> with your required JS files.
Replace the line 192 by including your new file and call your modal by passing your current store object in order to display your information in the modal.
Let me know if its help.

Has StackOverflow changed your code?
Launch demo modal
You have the classname within the href? This could be part of the problem.

Related

Updating HTML title after AJAX page load

When I load new pages via AJAX I need to of course update the HTML title to match the new page. The code below is something I have used successfully in past projects but for some reason it's not working here.
ajaxLoad = function(html) {
init();
// init google map
initMap();
// change html title
var HTMLtitle = $(".content > section:first-of-type").attr("data-title");
$(document).prop('title', HTMLtitle);
document.title = HTMLtitle;
// Used for popState event (back/forward browser buttons)
changedPage = true;
}
This is just a part of the javascript and you can view the rest in context if needed on the live site.
Live site: http://dma.nz/practice/
Click the top right links in the main nav to go to other pages. In my testing the title seems to update sometimes on the first page change but then never works on subsequent page changes. Most times it doesn't work at all and the title never updates. All of those top level pages have the proper HTML title defined in the data attribute, but some part of the function is failing and not updating the title and I cannot find where it's borked.
Can anyone please offer help on what I'm doing wrong or propose a better way to update the title on each AJAX page load?
As you're aware of the javascript error in initMap function
Uncaught TypeError: Cannot read property 'firstChild' of null
That exception breaks all your javascript below that line. Just fix it and your code will work, just like your main page: http://dma.nz/practice/

How to keep elements non-refreshed

The main goal is to keep non-refreshed the logotext <div class="small-7 medium-4 columns logo"> and the menu <nav class="pagedMenu" role="navigation">,without clipping on page refresh or while the content is loading from a page to another. Also, the menu state should be preserved from a page to another.
I've found here a possible solution that could solve the problem (you could use ajax to fetch the updated content and use jQuery to put the new content on the page and avoid the refresh entirely. Doing it that way, the existing data in the page would remain untouched. said #jfriend00)
So, I have tried to use an Ajax plugin (called AWS). In the AWS option page, I (suppose) that I've done the right thing pointing wrapper as Ajax container ID and also pagedMenu as Menu container class, Transition Effect Enabled, No ajax container IDs blank, no loader selected, having already a pulse loader implemented in the theme.
At this point, all I got it's a menu / side-menu (shiftnav) / pulse dot loader / content loading malfunction, generated perhaps by the wrong defined Ajax container id and/or menu container class(?) OR by a conflict with an existing JS / jQuery code, not so sure.
Also in Chrome console there is an error:
Uncaught SyntaxError: Unexpected token ;
(anonymous function) # ajaxify.js?ver=4.3.1:175
n.extend.each # jquery-2.1.4.min.js?ver=2.1.4:2
n.fn.n.each # jquery-2.1.4.min.js?ver=2.1.4:2
$.bind.$.ajax.success # ajaxify.js?ver=4.3.1:169
n.Callbacks.j # jquery-2.1.4.min.js?ver=2.1.4:2
n.Callbacks.k.fireWith # jquery-2.1.4.min.js?ver=2.1.4:2
x # jquery-2.1.4.min.js?ver=2.1.4:4
n.ajaxTransport.k.cors.a.crossDomain.send.b # jquery-2.1.4.min.js?ver=2.1.4:4
Everything is getting back to normal on page refresh but doesn't help at all, being useless.
I also have to mention that for the menu I've tried to keep the state using jQuery-Storage-API and storage=jQuery.sessionStorage; as you can see in mynewmenu.js file but that will not solve the non-refreshing elements problem.
The menu jsfiddle only, if this helps to have the whole picture, here thanks to #Diego Betto.
You can use this live link as example; there is a similar situation with the above described - Ajax implementation right(?) - and regarding the appearance, menu is kept non-refreshed from one page to another; if you browse Books, Works etc, menu sections you'll see; if there is a model that could be implemented here, I'll be glad to find it.
LE: meanwhile, I've tried another ajaxify solution made by #arvgta - special thanks - without success yet but as far as I've found from the Author, the defined elements should be div's with id's not classes. So, I'll try to find a way to modify somehow the code in order to have id instead on classes.
Also, I'll try to transform and implement in ajaxify.min.js file, the page-container element; jQuery('#page-container').ajaxify(); I'll come back with news.
LE2: I've tried to implement the solution using id's instead of classes but still, the pages are not loading correctly.
At this point we have ajax.min.js file updated with these lines:
(function($){
jQuery(document).ready(function(){
jQuery('#page-container').ajaxify({requestDelay:400,forms:false});
});
})(jQuery);
Also, I've modified the theme file to have id=page-container instead if class=page-container.
In these conditions, on menu click, the links are changed (like it should), menu/ logotext elements seems to working almost fine (sometimes get skippy changing position), but the content is not loading correctly in all cases; Same here, everything is getting back to normal on manual page refresh (f5), but doesn't help.
LE3: It looks like the conflict is (at least) between Revolution Slider plugin and Ajaxify.
errormessage="Revolution Slider Error: You have some jquery.js library include that comes after the revolution files js include." ;="" +=" This includes make eliminates the revolution slider libraries, and make it not work." "<="" span="">"
Site live link here. Any thoughts / alternative in this area? (not interested in using other different platforms, different WordPress themes, etc. just a workaround in this existing situation)
LE4: As far as I can see, there are many users that voted up the Jake Bown answer that could be indeed a solution; but I can't find the reason that didn't work correctly implemented into my theme (without errors) live link here The elements logotext / menu are still fading on refresh, are not kept non-refreshed. Any thoughts #Jake Bown / anyone?
LE final.
Buzinas delivered the closest answer for my needs, taking in consideration my site environment (plugins installed, etc).
From what you said I think I might have found the solution you're looking for - you want to load content dynamically whilst keeping the logo and navigation untouched? If so, this might be what you're looking for.
In the example, the pages are loaded in from a div within the page but could be used to load another URL or file:
$('.viewport ul li a').on('click', function(e) {
e.preventDefault();
var link = this.hash.substring(1, this.hash.length);
if($('.'+link).length) {
$('.viewport span.body').html($('.'+link).html());
}
});
TL;DR
I've created a plunker for you, take a look, and play with it as long as you can. You'll learn a lot from it!
I think you're trying too many things here, but didn't try the simplest:
The main goal is to keep non-refreshed the logotext and the menu ,without clipping on page refresh or while the content is loading from a page to another. Also the menu state should be preserved from a page to another.
If you want to do that, there are a few steps:
Create a 'master' page, that we're going to call index.html from now on.
So, our index must have the static part of our page, e.g menu, logo, footer etc.
Then, our 'subpages' must be cut down (no html, head, body, script, style tags, only the content that should be showed into our master page).
That done, now we must change our links to use AJAX instead of doing full refresh:
/* we add a 'click' event handler to our menu */
document.getElementById('menu-menu-2').addEventListener('click', function(e) {
var el = e.target;
/* then, we see if the element that was clicked is a anchor */
if (el.tagName === 'A') {
/* we prevent the default functionality of the anchor (i.e redirect to the page) */
e.preventDefault();
/* we show our spinner, so the user can see that something is loading */
spinner.classList.remove('hidden');
/* and we call our AJAX function, passing a function as the callback */
ajax(el.href, function(xhr) {
/* we get our main div, and we replace its HTML to the response that came
from the AJAX request */
document.getElementById('main').innerHTML = xhr.responseText;
/* since the request was finished, we hide our spinner again */
spinner.classList.add('hidden');
});
}
});
Ok, now our pages are already working via AJAX, and not reloading our static content.
But now, we see that we have some issues. For example, if someone tries to open one of our pages directly via URL, he'll see unstyled page, without the menu/logo etc. So, what should we do?
We have a few more steps now:
Simulate that our links are effectively transfering between pages using the History API:
/* inside our ajax callback, we save the fake-redirect we made into the pushState */
ajax(el.href, function(xhr) {
document.getElementById('main').innerHTML = xhr.responseText;
/* save the new html, so when the user uses the back button, we can load it again */
history.pushState({
html: main.innerHTML,
title: el.textContent + '| neuegrid'
}, '', el.href);
/* (...) */
});
/* and outside it, we add a 'popstate' event handler */
window.addEventListener('popstate', function(e) {
/* so, if we've saved the state before, we can restore it now */
if (e.state) {
document.getElementById('main').innerHTML = e.state.html;
document.title = e.state.title;
}
});
And we need that when the user enters directly to another page, e.g about-us, we redirect him to the index.html, and then load the about-us page from there.
So we create a redirect.js file, and we reference it in all of our
subpages:
/* save the page that the user tried to load into the sessionStorage */
sessionStorage.setItem('page', location.pathname);
/* and them, we redirect him to our main page */
location.replace('/');
And then, in our index.html page, we see if there is any page in the sessionStorage, and we load it, if there is, otherwise we load our home page.
var page = sessionStorage.getItem('page') || 'home';
/* we look into the menu items, and find which has an href attribute
ending with the page's URL we wanna load */
document.querySelector('#menu-menu-2 > li > a[href$="' + page + '"').click();
And that's it, we're done now. Take a look at the plunker I've been making to you.
And play with it as long as you can, so you'll learn a lot from it.
I hope I could help you! :)
Note: Just for reference, this is our ajax function:
function ajax(url, callback, method, params) {
if (!method) method = 'GET';
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (callback) xhr.addEventListener('load', function() {
callback.call(this, xhr);
});
if (params) {
params = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
xhr.send(params);
} else {
xhr.send();
}
}
GOING AJAXED WITH WORDPRESS
demo: http://so.devilmaycode.it/how-to-keep-elements-non-refreshed/
follow these simple steps (let's take as example theme "twentyfifteen" on the WP templates folder):
edit single.php, page.php, index.php and all other pages having get_header() and get_footer() functions and replace it respectively with below code:
NOTE: this is important because if someone (ex: search-engine) reach your pages directly from the link, it is still fully available and 100% working. (useful for SEO)
<?php
//get_header()
if(!isset($_REQUEST['ajax'])){
get_header();
}
?>
<!-- other code --->
<?php
//get_footer()
if(!isset($_REQUEST['ajax'])){
get_footer();
}
?>
open the header.php add the below code inside the <head> section at the very end
<script>
!(function($) {
$(function() {
$('.menu-item a, .widget-area a, .page_item a').on('click', function(e) {
e.preventDefault();
var href = this.href;
var query = href ? (href + (!/\?/g.test(href) ? '?' : '&') + 'ajax=1') : window.location;
/* IMPLEMENT SOME LOGIG HERE BEFORE PAGE LOAD */
/* ex: kill instance of running plugins */
$('#content').hide().empty().load(query, function() {
/* IMPLEMENT SOME LOGIG HERE AFTER PAGE IS LOADED */
/* ex: refresh or run a new plugin instance for this page */
jQuery(this).show();
});
});
});
})(jQuery);
</script>
in the header.php file put the code below at the end of the file, 90% of times you need it under the navigation. In this case we already have this on the "twentyfifteen" theme.
NB: most probably you have the opening tag <div id="content" class="site-content"> inside the header.php file and the closing tag </div> on the footer.php file, this doesn't matter, you can leave it as is.
<div id="content"></div>
NOTE: consider this a proof of concept; it may work as is, but you still need to tailor it to suit your needs; you may need to:
Add a menu (in case it is not already set) by going under Appeareace > Menus > [check Primary Menu] > Save Menu in order to activate the menu. it's tested and working.
You may want to add some other class to the jQuery function like .widget-area a in order to ajax also widget links.
if you are using 3d party plugins you may need to ensure that all dependencies of each plugin are loaded also on the main page from where you want everything is displayed without refreshing content.
you may need to check and kill those 3d party plugin before a new page load and run or refresh plugin needed in the loaded page.

Anchor click even not firing after PJAX page load

I am having a pretty strange problem with a website I am messing around with, and I can't wrap my head around what may be going wrong. I am using PJAX on the site, and the have a div in my body with the id of #page-contents.
The code I am using to setup PJAX is as follows...
<script type="text/javascript">
$(function(){
$(document).pjax('a', '#page-contents', {
fragment: '#page-contents',
timeout: 2000
});
});
</script>
I know that the setup is correct because I edited the PJAX file to fire an alert whenever it swapped out the content of my #page-contents div, and I do see that alert when I would expect to (i.e., on link clicks).
I have a navbar along the top (a bootstrap navbar) and I was initially having trouble keeping track of which navbar item would be marked as active. I have solved this problem using the following javascript code.
<script type="text/javascript">
$("a").click(function() {
$(".navbar-nav li").removeClass("active");
var nextPage = $(this).attr("href");
nextPage = nextPage.substring(nextPage.indexOf(window.location.hostname) + window.location.hostname.length);
switch(true) {
case nextPage == "/about":
$("#about-nav").addClass("active");
break;
case nextPage == "/contact":
$("#contact-nav").addClass("active");
break;
case nextPage == "/resume":
$("#resume-nav").addClass("active");
break;
case nextPage.indexOf("/projects") != -1:
$("#projects-nav").addClass("active");
break;
default:
break;
}
});
</script>
This works fine for all links I have in my navbar, but I have found that any links I have inside my #page-contents div will not trigger my above script. I know that PJAX is still working as the page changes and the alert I inserted displays.
A few things I have found in my own testing:
I have also found that if I directly load an address that contains a non-navbar link and then click that link, it will work. But coming back to that page via a pjax reload and then clicking the link will not fire my event.
Adding a test class to one of my anchors and then associating some event with that class has the same problems.
Does anybody know why my script would not be getting executing? Or maybe I am just missing something obvious.
Thank you in advance!
P.S.: The website in question is my personal site I am working on, the link is http://rosshays.me, the page I first noticed this on was my about page. (The site is a work in progress as you'll clearly see.) As mentioned about, going to the about page directly and clicking the link will work, but if you navigate to the about page and then try to click the link in the page, it will not work.
Ross-
I had a similar issue and I know how to solve this; this script is not binding to the new elements because it is not being re-ran on the new elements once they are loaded.
Please put your function in an external .js file. Once complete, you can add this script to your header:
$(document).on('pjax:complete', function() {
$.ajaxSetup({ cache: true});
$.getScript("YOUR SCRIPT FILE PATH HERE', true);?>");
});
You will have to add more $.getScript calls for any other javascript/jQuery that is needed in order to enable the events you want to take place. (Example: you may need to reload jQuery)
This will re-apply the jquery and javascript to the new elements that are loaded via PJAX.
*One thing to note: If you are using twitter bootstrap, do not re-call the bootstrap script with $.getScript as it will cancel itself out on every other re-load.

Dynamically loaded javascript doesn't work second time loaded

I am working on a webpage that uses a JQuery UI dialog (in modal mode) to display a form that is dynamically generated using Django. The basic flow is:
the user clicks a button
jquery (using AJAX) issues a get request that returns the html for the form which is then used to fill the dialog
The html contains a script tag that handles some UI on the form which loads fine and works as expected
the user than fills out the form and clicks "Done" and the form is submitted.
The issue comes in when the user makes an error on the form. The server responds to the post request (that submits the form) with the original form (including the script) modified to show the errors. This second time the script is loaded it gets a "Uncaught ReferenceError: $ is not defined (anonymous function)" The script is exactly the same as before when it worked fine. To be clear throughout this entire process the page is never refreshed.
Here is the gist of the javascript that takes care of the modal:
var add_container = $("#add_container");
add_container.dialog({...})
function show_form(form,response_func) {
add_container.html(form);
add_container.dialog("open");
$("#add_form").submit(function (event) {
return submit_form($(this),response_func);
});
}
function submit_form(form,response_func) {
add_container.append('<p>Adding...</p>');
//this is a trick to upload a file without reloading the page
form.attr('target','upload_target');
$('#upload_target').load(function() {
var response = $('#upload_target').contents().find('body').html();
add_container.dialog("close");
resp_obj = $(response)
if (resp_obj.is('form')) {
//***this is what reloads the form when there is an error
show_form(response,response_func);
} else {
response_func(resp_obj);
}
});
}
$('#add_link').click(add_link);
function add_link() {
$.get('/add_link', function(data) {
function add_response(response) {
//handle successful submission
}
show_form(data,add_response);
});
}
//...more stuff that is not important
This is the gist of the html returned from /add_link
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- Dynamically generated form here !-->
</form>
The add_form.js is a pretty standard javascript file that uses jQuery. Its starts with $(document).ready(function () {...} ) and the first $ is where the ReferenceError occurs
The form needs to be dynamically generated based on what is clicked so I can't just put everything statically on the page. The script is not dynamically generated so it doesn't necessarily need to be dynamically loaded but I wasn't sure how to keep it in its own file, and also only have it run when the form is loaded. I am open to suggestions of alternative ways to accomplish the same effect.
Your form action is pointing to a different relative path to the one containing the jQuery framework script, etc.
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<!-- src="/scripts" -->
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- action="/add_link" -->
To make sure it's loading the framework after the form submission, just use something like the developer tools on your browser and check the head tag for the jQuery script src. Is it still there?
Thanks to MelanciaUK I realized that when I submitted my form to the iFrame the response was getting sent first to there where the script would run and error because the iFrame is treated as its own page and doesn't have access to jQuery loaded on the main page.
I decided to solve the problem by eliminating the dynamic loading of the add_form script and simply load it when the page loads just like all my other scripts. I created a custom jQuery event (using .trigger) in order to only have the script run when the add form is opened. This worked exactly the way I wanted it to.
Hope this helps anyone with a similar problem. If you have any questions feel free to ask!

Simple Javascript Doesn't Work Right

I use the tabber script shown on http://www.barelyfitz.com/projects/tabber/ to provide a tabbed page. Generally it works well, and my only complaint is that the tabs don't show until the content has fully loaded, and then there is a jump as the screen writes itself properly. (See www.littlehotels.co.uk/spain/noves.php for an example of what I mean.)
I thought the solution would be to hide the div containing all the tabbed content like this
<div class="tabber" id="tabber" style="display:none">
and then reveal it with a small javascript function which is called by
<body onLoad="ShowTabber()">
The javascript itself is
<script type="text/javascript">
function ShowTabber() {
document.getElementById('tabber').style.display = "block";
}
</script>
My little function appears to stop the external javascript (tabber.js) from working because the page displays the content of all the tabs in line, without the the tabs themselves at the top. This is the same result as if I delete the reference to the external script from the of the page.
What am I doing wrong?
More explanation:
When the tabber.js file is missing, the page displays the content of all the tabs one after the other(as you would expect). Running the script as explained above has exactly the same effect; hence I am concluding that the script blocks the main javascript from running.
'onLoad': function(argsObj) {
/* Display an alert only after tab */
if (argsObj.tabber.id == 'tab') {
alert('Finished loading tab!');
}
}
By default select a tab.Then after completion loading that tab it will show a message.
see here
Well, I solved the problem (sort of) with jQuery, but it has now raised another problem.
In response to PSR, I looked more deeply into jQuery. It would have been too complicated to change over to .tabs(), but I did use jQuery to hide and show some divs at the appropriate moments.
I placed a simple little line in fron of the tabber div to show a "Loading" message.
<div id="loading" align="center" style="position:relative;top:70px"><h6>Loading ...</h6></div>
Then I put this script in the head, under the jQuery line.
<script type="text/javascript">
$(document).ready(function(){
$("#tabber").hide();
$("#loading").hide();
$("#loading").fadeIn(1000);
});
$(window).load(function(){
$("#loading").hide();
$("#tabber").fadeIn(300);
});
function checkResize(id){
var win=document.getElementById(id).contentWindow.document.body.scrollHeight;
alert(win);
}
</script>
That works fine, but a couple of the tabs have iframes for their content, and this script breaks autoResize script I use on those iframes. I'll open a new question to see if anyone has an answer to that.

Categories

Resources