I'm generating elements from a list and each of these will have a click event.
This is all in the same partial view that gets refreshed every X seconds elapsed.
The first initial load doesn't work. Every auto refresh of the partial after works fine.
all (document).ready events fire.
Other code outside of the click events fire just fine.
Loop in view
<div id="#overview.GroupType.Name" class="tile #overview.AlertType.MetroBG ui-widget-content draggable" data-role="tile" style="z-index: 2;">
<div class="tile-content iconic" style="z-index: 2;">
<span class="icon #overview.AlertType.MetroImage #overview.AlertType.MetroFG"></span>
<span class="tile-badge #overview.AlertType.MetroBadgeBG #overview.AlertType.MetroBadgeFG">#overview.BadgeCount.ToString()</span>
<span class="tile-label no-padding fg-white">#overview.GroupType.Description</span>
</div>
</div>
loop in script section of (document).ready generates the following
$('##overview.GroupType.Name').on("click", function () {
alert('click');
$.ajax({
type: 'GET',
url: '#Url.Action("LoadDetail", "Home")',
dataType: 'html',
data: { 'groupName': '#overview.GroupType.Name' },
async: true,
cache: false,
success: function (data) {
$("#monitorDetail").html(data);
},
error: function (xhr, status) {
}
})
});
I read a few posts saying you have to use .on("click" ...) so I'm not sure what else to look into.
$('body').on('click', '##overview.GroupType.Name', function(){
// do stuff here
});
You could replace the body selector with the non-dynamic parent of your dynamic div . I hope that makes sense.
That's what I got from your question, but still a bit confusing:
1) You are loading something dynamically using ajax into the main view every 5s.
2) When this happens you need to bind events to something inside this dynamic content.
3) It's not working (dahh for sure not, you asked us).
Solution:
You must bind any event after the Partial Refresh, at the success method. Why? Because you have changed the DOM and the first $('document').ready did't find out this content loaded with ajax at the first time.
$('##overview.GroupType.Name').on("click", function () {
alert('click');
$.ajax({
type: 'GET',
url: '#Url.Action("LoadDetail", "Home")',
dataType: 'html',
data: { 'groupName': '#overview.GroupType.Name' },
async: true,
cache: false,
success: function (data) {
$("#monitorDetail").html(data);
//Bind the events to for anything after loading the content
},
error: function (xhr, status) {
}
})
});
And this script above will work only if the script is inside the main view, because It's need Razor Server Render to build the id '##overview.GroupType.Name'. You can't have dynamic script at the partial. Ajax will not execute this scripts.
Related
I got a html page #main that is fully loaded by a javascript function loadNe(). After the page gets fully loaded by the Ajax call, I want some tooltips to be shown when mouseovering some rows. Those tooltips makes Ajax requests to exhibit its content. The problem is:
The "open:" function inside tooltip() is probably never being executed because nothing gets printed in the console by the console.log() inside it. And also no network requests are sent to the tooltip's ajax URL. But still, the tooltip is working when I mouseover the elements, it shows me the title's tag content "Loading...".
What can be going wrong here?
function loadNe(ne){
$.ajax({
type: "GET",
url: "/NOKIA/fx-load.php?label=" + ne,
dataType: "text",
success: function (data){
var content = fillResult(data);
$("#main").html(content).hide();
$("#main").fadeIn("slow");
$(".sfp").tooltip({
track: true,
open: function (event, ui){
var sfp = $(this).text();
console.log("1-executing.."+sfp);
$.ajax({
type: "GET",
url: "/NOKIA/sfp-load.php?sfp="+sfp,
dataType: "json",
success: function(data){
console.log("2-executing.."+data["reach"]);
var html = "<tr><td>Alance: "+data["reach"]+"</td></tr>"+
"<tr><td>Tamanho de onda: "+data["wavelength"]+"</td></tr>"+
"<tr><td>Limiar Rx: "+data["rx_min"]+"</td></tr>";
$(".sfp").tooltip('option','content',html);
}
});
}
});
}
});
}
The problem was I was loading the bootstrap.min.js before the js-ui.min.js. The tooltip() function was executing the bootstrap library instead of the js-ui. So I inverted the order of loading as it is down here:
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js-ui/jquery-ui.min.js"></script>
I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});
My slick carousel is defined inside the body as:
<div class="election-carousel">
<?php echo Election.php::createView(); ?>
</div>
Items of the carousel are created using an interval ajax call but the carousel is not updating:
setInterval(function(){
$.ajax({
url: '../class/Election.php?createView=1',
success: function (html) {
$(".election-carousel").html(html);
},
type: 'GET'
});
}, 5000);
I checked the page source after loading the carousel's items and it's there. I also tried .slick("unslick") then reinitialize but it doesn't work. It seems to be the DOM which is not updating?
You should be doing slickAdd and slickRemove each time you load data
setInterval(function(){
$.ajax({
url: '../class/Erection.php?createView=1',
success: function (html) {
$('.erection-carousel').slick('slickRemove',0); //remove elements starting with child 0
$('.erection-carousel').slick('slickAdd',html); //re-add new html
},
type: 'GET'
});
}, 5000);
I have an ajax call that is populating a portion of my page with the html it returning in the success callback:
function LoadCurrentCourses(masterKey, status) {
status = 'S';
$.ajax({
type: "GET",
url: "/Home/LoadCurrentCourses/?masterKey=" + masterKey + "&status=" + status,
dataType: "html",
success: function (evt) {
$('#currentCourses').fadeIn(1500, function () { $('#currentCourses').html(evt) });
},
error: function (req, status, error) {
$('#currentCourses').html("<p>Error occured retrieving current courses</p>");
}
});
}
the #currentCourses markup just has a header and loading .gif in there.
<div class="span4 moduleBox" id="currentCourses">
<h2>Current Courses</h2>
<img style="margin-left: 45%; margin-top: 5%; margin-bottom: 5%;" src="~/Images/11.gif" />
</div>
The ajax is being called from my main page on doc.ready():
<script>
$(document).ready(function () {
var masterKey = '#Model.MasterKey';
//load degree overview
LoadCurrentCourses(masterKey);
});
</script>
What I am trying to do is one the data gets returned I would like the html to slowly fade in to the main page, replacing the gif and header. Right now it works fine, everything loads, and is replaced, but I can't seem to figure out where I should put the jQuery .fadein() method.
Any ideas?
You should load the text before fading in
success: function (evt) {
$('#currentCourses').html(evt);
$('#currentCourses').fadeIn(1500);
},
You may also need to fadeout or hide that container before fading in, or it will appear to do nothing and just load the new data.
Should be like:
success: function (evt) {
$('#currentCourses').html( evt ).fadeIn(1500);
}
Fade in after the element is populated, otherwise calling .html() inside the .fadeIn() callback will result in:
fade--(fade ends)-->--(HTML applied)
I am loading content, mostly images, through this ajax call, and would like to fade the div in only when all of the images are completely loaded. For this reason, I thought that I should use .ready, so that all of the content was loaded before I use jquery to fade it in, but for some reason the images are not completely loaded when the div gets faded in, which makes it seem like it is not waiting for everything to load.
I am basically wanting to build a preload, for this AJAX content
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: true,
success: function (html) {
$('#content').html(html);
$("#slider").easySlider();
$(this).ready(function() {
$('#body').fadeIn('slow');
$('#loader').fadeOut('slow');
});
}
});
Thank you for the help in advance. I am still a beginner.
example:
Edit:
Oh, now I see what's your problem!
When the success() function is fired, you gotta add a .load event to the images inside #content!
You gotta do something like this
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#loader').fadeIn('slow');
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: true,
success: function (html) {
$('#content').html(html);
$("#slider").easySlider();
$('#content img').load(function(){
$('#body').fadeIn('slow');
$('#loader').fadeOut('slow');
});
}
});
}