Updating page content except one div using Ajax - javascript

I am trying to make a website that loads all pages using AJAX. Here's a simple piece of JS that does that:
$.ajax({
url: url,
type: 'GET',
success: function(html) {
document.open();
document.write(html);
document.close();
}
});
This obviously works and updates my current page content.
The problem is I want to keep one div unchanged (let's call it .player-wrapper). This div is actually an <audio> wrapper which I want to keep playing (and this is the reason I AJAXified the entire website). Is this possible?

Every time you render a page, you can initialize plugins/libraries like this:
const App = function() {
return {
init: function() {
// Do all your JS stuff here
console.log('App initialized.');
},
render: function(url) {
$.get(url, data => {
$('main').html(data);
}, 'html').done(() => {
this.init();
});
}
};
}();
$(function() {
App.init();
$(document).on('click', '[data-page="ajax"]', function (e) {
e.preventDefault();
const url = $(this).attr('href');
App.render(url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<audio class="player-wrapper" src="https://www.free-stock-music.com/music/alexander-nakarada-wintersong.mp3" controls autoplay></audio>
<main>
<h1>Initial page.</h1>
</main>
<nav>
Go to dummy page
</nav>

If you want to keep the audio tag with the player-wrapper class let's take this html as our base:
<body>
<audio class="player-wrapper"></audio>
<div class="page-content"></div>
</body>
Then with the following code you can place the html you received from the ajax request:
document.querySelector('.page-content').innerHTML = html;
Just don't write the html to the document, but place it in an already existing element like the div with the page-content class in this example.
And when you need to execute script tags in the html you can use jQuery's append method (since you are already using jQuery)
$('.page-content').append(html);

One thing you can do is copy the .player-wrapper before you write.
$(".overridebutton").on("click", function () {
var html = '<div class="override">Im a new div overriding everything except player-wrapper</div>';
var exception = $(".player-wrapper").html();
console.log(exception);
document.write(html + exception);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="everything">
<div class="sub-1">
Hello Im sub-1
</div>
<div class="sub-2">
Hello Im sub-2
</div>
<div class="sub-3">
Hello Im sub-3
</div>
<div class="player-wrapper">
I am player wrapper
</div>
</div>
<button class="overridebutton">Override</button>

Related

JavaScript file doesn't load after page transition with barba.js

I have a website with a link. When I click the link I want a smooth page transition to the next page using jQuery. I got the the HTML elements inside the barba DOM to fade out. But when the next page tries to load, all BUT the JavaScript loads.
This is my code:
(index.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<div class="container">
<span class="text1">Hey There!</span>
<span class="text2">This is my portfolio!</span>
<a id="homeLink" href="./home.html">Click me to continue</a>
</div>
</div>
</div>
<script>
$('document').ready(function(){
var transEffect = Barba.BaseTransition.extend({
start: function(){
this.newContainerLoading.then(val => this.fadeInNewcontent($(this.newContainer)));
},
fadeInNewcontent: function(nc) {
nc.hide();
console.log('stuff should be hidden');
var $el = $(this.newContainer);
var _this = this;
$(this.oldContainer).fadeOut(1000).promise().done(() => {
nc.css('visibility', 'visible');
nc.fadeIn(1000, function(){
console.log('new content should fade in.');
_this.done();
})
});
}
});
Barba.Pjax.getTransition = function() {
return transEffect;
}
Barba.Pjax.start();
});
</script>
I can see the the console logs in the console but JavaScript doesn't load.
This is the page I'm trying to load:
(home.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<canvas></canvas>
<script src="canvas.js"></script>
</div>
</div>
I get no errors whatsoever.
Also I have seen a question on here with the same problem as mine, but it was very unclear. (and does not have any answers so far)
Thanks!
In Barba, scripts don't evaluated when loading a new container. It can be done easily using Events.
Barba.Dispatcher.on('newPageReady', function (currentStatus, oldStatus, container) {
$(container).find('script').each(function (i, script) {
var $script = $(script);
$.ajax({
url: $script.attr('src'),
cache: true,
dataType: 'script',
success: function () {
$script.trigger('load');
}
});
});
});
Add this line:
document.getElementsByTagName("head")[0].innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">";
inside below function
fadeInNewcontent: function(nc) {
}

Ajax anchor Link trigger not working

I am using html2canvas javascript to convert html div to image file. All script are working good and it converts html div to image properly.
But when I am adding response(anchor link) to href and triggering it using ajax it is not triggering anchor link.
Here is my code,
Html code:
<div id="mainDiv">
<h1>Heading H1</h1>
<p>Download Image using ajax and php</p>
</div>
<div>
<a id="download">Download Image</a><br/>
<a id="download-image" href="" download>Download</a>
</div>
Ajax code
<script>
$('#download').on('click', function () {
html2canvas([document.getElementById('mainDiv')], {
onrendered: function (canvas) {
var imagedata = canvas.toDataURL('image/png');
var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_image.php',
data: {
imgdata:imgdata
},
type: 'post',
success: function (response) {
$('#download-image').attr('href', response).trigger('click');
//$('#downlaod-image').trigger('click');
}
});
}
});
});
</script>
Clicking the link will actually reload your page. It will still execute html2canvas(), but the response from the Ajax call will never be processed, as by that time the page has already been reloaded.
So cancel the default hyperlink action by adding a return false just before the end of the click handler (after the call to html2canvas).

Dynamic load of whole jstree

I have this working example of jstree properly initiated allowing to browse through tree structure and trigger action when user clicks the node: https://jsfiddle.net/8v4jc14s/.
When I try to load the tree dynamically it's not working:
<div id="container">
<button onclick="load()">Load tree</button>
</div>
<script>
$(function () {
$('#tree_div')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
});
function load() {
document.getElementById("container").innerHTML = "<div id=\"tree_div\"><ul><li id=\"Root\">Root<ul><li id=\"Sub\">Sub</li></ul></li></ul></div>";
}
</script>
Is there a way to "initiate" the tree after dynamic load?
You can copy but you cannot bind events to copied element since you have initialized only one instance of jstree.
If you want another jstree, you need to make another instance.
You can check this:
$(function () {
$('#tree_div')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
attach();
second();
});
//just copies UI
function attach(){
var $elem = $("#tree_div").clone(true, true);
$("#myTest").append($elem);
}
//for another instance
function second(){
$('#yourTest')
.jstree()
.on('changed.jstree', function (e, data) {
alert(data.selected);
});
}
https://jsfiddle.net/8v4jc14s/3/
During further research I have found this question: How do you execute a dynamically loaded JavaScript block?
I have used answer from Roman coming up with below code that looks to be working well.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="container">
<button onclick="load()">Load tree</button>
</div>
<script>
function load() {
// Clear container DIV to avoid adding tree div multiple times on multiple clicks
document.getElementById('container').innerHTML = "<button onclick=\"load()\">Load tree</button>";
// Creating new DIV element
var newdiv = document.createElement('div');
// Creating a jstree structure under newly created DIV
newdiv.innerHTML = "<div id=\"tree_div\"><ul><li id=\"Root\">Root<ul><li id=\"Sub\">Sub</li></ul></li></ul></div>";
// Creating new SCRIPT element
var script = document.createElement('script');
// Creating SCRIPT element content
script.innerHTML = "$(function () {$('#tree_div').jstree().on('changed.jstree', function (e, data) {alert(data.selected);});});";
// Adding SCRIPT element to newly created DIV
newdiv.appendChild(script);
// Finally updating "container" DIV
document.getElementById('container').appendChild(newdiv);
}
</script>
Hope this helps others like me lost in mysteries of JS :)

How to properly load html code on a jquery dialog?

im trying to load a piece of html inside a jquery dialog, this piece of code is located in a separated file, but sometimes fails to load it right. It happens like this :
This is how it should have been displayed.
But sometimes(many times actually) does this:
This is the code that calls the dialog
.click(function(){
var me = this;
$.ajax({
type:"POST",
url:"../CuentaEquipo.php",
dataType: "json",
data:"idEquipo="+$(this).attr("idEquipo")+"&idTorneo="+$(this).attr("idTorneo")+"&action=100",
success:function(data){
if(data.data == 1){
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
cuentas.dialog('open');
}
And this is the code i'm trying to load (AdministracionCuentaEquipo.html)
<script type="text/javascript">
$("#accioncuentas").tabs();
$(".test").button().click(function(){alert("ASDF")});
</script>
<div id="accioncuentas">
<ul>
<li>Abonos</li>
<li>Cargos</li>
<li>Saldos</li>
</ul>
<div id="abonos">
<button class="test">HI</button>
</div>
<div id="cargos">
<button class="test">HI</button>
</div>
<div id="saldos">
<button class="test">HI</button>
</div>
</div>
The only thing that works is closing and opening when this happens, but it's very annoying to do that. It's there any fix or i'm doing something wrong with the ajax or anything else?
Thanks .
I think the problem is that you are creating/opening the dialog before the HTML has properly been parsed.
From the jQuery documentation:
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed.
So try changing this code:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
to:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html", function(e)
{
$("#cuentas").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
EDIT: the line $("#accioncuentas").tabs(); might also fire too early, so you could change that script tag to wrap it in a function and call that function in your other code.
Example:
<script type="text/javascript">
function InitializeTabs()
{
$("#accioncuentas").tabs();
}
</script>
and then add the line InitializeTabs(); to your code, for example above the line $("#cuentas").dialog({.
SECOND EDIT: I actually think Dasarp is correct in saying that the $("#accioncuentas").tabs(); is the main problem. Either wrap it in a function as I suggested, or move the entire <script> tag down to the bottom of the file (below all your HTML).

Redirecting to a page via ajax

I am trying to Ajaxify a normal page redirect.
ASPX (View: Parent.aspx):
<a id="GetContent" href="#">Go to Content Page</a>
ASPX (View: Content.aspx):
<div id="content">
...
</div>
Controller (ContentController.cs):
public ActionResult Index(id)
{
var content = _db.GetContent(id);
return View("Content");
}
JS:
$(document).on("click", "#GetContent", function () {
location.href = "/Index/3";
});
I tried this. This works, however, the url in the URL bar does not change.
$(document).on("click", "#GetContent", function () {
$("#content").load("/Index/3");
});
So when you click on the link, currently it posts back normally and then redirects to ~/Content/3 (i.e. no ajax). What I want is to immediately go to the Content page, and then display a loading indicator while the content is being fetched. I know I probably have to use jQuery.load() to do this, but not quite sure how to put things together.
Any help is appreciated!
I think this is what you are looking to do...
Index.aspx:
<div id="content">
...
</div>
<script>
$(document).ready(function() {
$.ajax({
url: '/Content/Details/3', // <-- Can use #Html.ActionLink here, to utilize routing a bit.
success: function(data) {
$('#content').html(data);
}
});
});
</script>
ContentController.cs:
public ActionResult Index(id)
{
return View("Index");
}
public ActionResult Details(id)
{
var content = _db.GetContent(id);
return PartialView("_Details", content);
}
If you put a loader.gif in the div initially I think you'll get the behavior you are looking for. You'll also need to make sure you have the _Details view created, and displaying whatever is in your model (var content).
i would link jquery (through
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
) and then use
var checking = "<img src='ajax-loader.gif'/>";
$("#content").innerHTML=checking
$("#content").load("/content/3");
to load it in the page

Categories

Resources