document.ready() equivalent for AJAX loaded content - javascript

I have a AJAX call that adds nested divs (with the class .song_block) to a div (#song_list) on the page. I have a button that I want to hide once the count of nested divs reaches a certain number.
Here is my script
<script type="text/javascript">
$(document).ready(function() {
if($("#song_list").find('.song_block').length == 100){
$('#loadmore').hide();
}
});
</script>
Here is the AJAX call
<script type="text/javascript">
$(document).ready(function() {
$('#loadmore').on('click', function() {
$('#loadmore').hide();
$('#loadmore-gif').show();
$.ajax({
type: "GET",
url: "/loadmore/",
data: {
'slug': $('.dj_slug').text().trim(),
'song_rank': $("#song_list").find('.song_block').length
},
}).done(function (response) {
$('#song_list').append(response);
$('#loadmore').show();
$('#loadmore-gif').hide();
});
});
});
</script>
Now this doesn't work since $(document).ready() doesn't work for AJAX loaded content. How can I handle such a situation using javascript?

The equivalent to $(document).ready for AJAX is ajaxComplete.
So here is the code:
$(document).ajaxComplete(function(){
//your code here
});
Thanks to #usman on the answer here Document Ready equivalent for ajax-loaded content via jQuery Mobile accordion

Create a function
function hideLoadMore() {
if($("#song_list").find('.song_block').length == 100){
$('#loadmore').hide();
}
}
And use it when DOM was loaded and when related ajax requests are done
$(hideLoadMore);
$(function() {
$('#loadmore').click(function(){
$.ajax(...).done(/*perform dom insertion*/).done(hideLoadMore);
});
});

Related

when scroll down, data is loaded by ajax but click trigger is not working jquery

i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.

refresh page on success

I'm using the javascript code below to load recrefresh.php when the page initially loads. When the function ajaxvote is executed I want the following div to refresh:
<div class="recrefresh"></div>
I tried adding the following after success:, but the div doesn't refresh after executing ajaxvote:
$.get('recrefresh.php', function(data) {
$('.recrefresh').html(data);
});
Entire Script:
<div class="recrefresh"></div>
<script type="text/javascript">
$.get('recrefresh.php', function(data) {
$('.recrefresh').html(data);
});
</script>
<script>
$('.ajaxvote').click(function(e){
e.preventDefault(); // Prevents default link action
$.ajax({
url: $(this).attr('href'),
success: function(data){
alert("Vote Saved.");
$.get('recrefresh.php', function(data) {
$('.recrefresh').html(data);
});
}
});
});
</script>
use this
<script>
$(document).ready(function(){
//run function here
refreshMyDiv();
//click event for dynamically generated elements
$('.recrefresh').on('click' , '.ajaxvote' , function(){
//run function inside click
refreshMyDiv();
});
});
// function to refresh the .recrefresh div
function refreshMyDiv(){
$.get('recrefresh.php', function(data) {
$('.recrefresh').html(data);
});
}
</script>
To solve this issue take parent div to <div class="recrefresh"></div> because direct div does not load sometimes so wrap this div with other div say for ex.
<div class="recrefresh_parent"><div class="recrefresh"></div></div>
and use recrefresh_parent to refresh table.
There is the way to refresh or load div after ajax call:
$('.recrefresh_parent').load("recrefresh.php .recrefresh_parent");

using the $.ajax function to fetch a specific id

I'm learning how to use jQuery methods of making AJAX calls, at the moment what I would like to know is how I use the $.ajax function to return a certain elements content. I realize this can be done easily enough using .load() but would like to get the results using .ajax(). At the moment I am fetching the clicked href attribute and returning the whole pages data when I would like to just return the #container content of the page?
Sample code being used:
jQuery(document).ready(function() {
/* Ajax load in portfolio pages */
var ajaxLoader = $('#ajax-loader');
var folioContainer = $('#folio-container');
ajaxLoader.hide();
$('div.wp-pagenavi a', 'div#content').click(function(e) {
$.ajax({
url : this.href,
method : 'get',
success : function(data){
folioContainer.html(data);
}
});
e.preventDefault();
});
});
You should be able to .filter() the response from the server to select only the data you want:
success : function(data){
folioContainer.html($(data).filter('#container'));
}
Here's a jsfiddle of this solution: http://jsfiddle.net/jasper/5HSzB/
Here's an optimized version of your code:
jQuery(function($) {
/* Ajax load in portfolio pages */
var ajaxLoader = $('#ajax-loader').hide();
$('.wp-pagenavi', '#content').find('a').click(function(e) {
$.ajax({
url : this.href,
method : 'get',
success : function(data){
$('#folio-container').html($(data).filter('#container'));
}
});
e.preventDefault();
});
});
You may be better off using the load method http://api.jquery.com/load/ , read the section "Loading Page Fragments"
not sure but try:
jQuery(document).ready(function() {
/* Ajax load in portfolio pages */
$('#ajax-loader').hide();
$('div.wp-pagenavi a', 'div#content').click(function(e) {
$.load(this.href + ' #folio-container');
e.preventDefault();
});
});

jQuery document ready after ajax request

I'm having problems with updating elements that are not ready after an ajax request.
If I run my myFunction() function on page load like so:
$(function() {
myFunction();
}
I have no problems at all. But if I then use something like
$.ajax({
url: this.href,
dataType: "script",
complete: function(xhr, status) {
myFunction();
}
});
which returns $(".myElement").replaceWith("htmlHere"). The elements are simply not ready when the complete event fires. If I set a delay in there it works fine again.
Is there any other event that gets fired other than 'complete' when the DOM is ready?
Update:
Here's the actual code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
myFunction();
});
function myFunction() {
// Modify the dom in here
}
The missing ); was just a typo on my part.
Ive tried using success now instead of complete and it doesn't appear to make any difference.
I have set up a jsfiddle based on your code, and it seems to be working.
This is the current code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
});
function myFunction() {
$("span").replaceWith("<p>test</p>");
}
And it replaces span tag with a paragraph. Please check it and compare with your code. If it is the same, then your problem somewhere other than this function (maybe in myFunction?).
You can use $(document).ready(function() { ... }); to wrap up anything you want fired when the DOM has loaded. Your ajax request could be placed inside the document.ready if you want this to wait until the dom has loaded.
If you want to wait until the ajax has loaded its resource then you should use ajax.success rather than complete.
Just change complete: to success: in your $.ajax() call:
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
//make your DOM changes here
myFunction();
}
});
The success function will run once the AJAX request receives a successful response. So make your DOM changes within that function, and then run myFunction().
Edit
You seem to be trying to make the DOM changes using your myFunction(). But if you don't first insert the HTML received in the AJAX response into the DOM, then there will be nothing for myFunction() to modify. If this is indeed what's happening, then you have two options:
Insert the response HTML into the DOM, then call myFunction() (and all of this should happen within the success callback function).
Pass the AJAX response to myFunction() as an argument, so that myFunction() can handle the DOM insertion and then do the necessary modification.
There is a event that triggers after every ajax call. It is called ajaxComplete.
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
So you can
function Init(){
// stuff here
}
$(document).ready(function()
Init();
});
$(document).ajaxComplete(function()
Init();
});
You are missing the closing parenthesis of the document ready wrapper function.
$(function() {
myFunction();
});
Note the }); at the end.
$(function() {
myFunction();
}
should be
$(document).ready(function() {
myFunction();
});
Or incase you want the ajax to run on load. Do
$(document).ready(function() {
$.ajax();
});

Question about Javascript (Jquery) and GET

After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.

Categories