How to load function after ajax load all DOM elements - javascript

I have an issue with a function that should be loaded after all content is ready.
I have a massive ajax call 1700 line of code.
How my code works: php file getting data from 3 tables in my database and converting it to JSON. I opening the JSON file and creating 1 element for 1 database result.
For now, I have around 100 results but I will have around 1000 in the final step. So I create loading to put before the page will be loaded. But because the main content is created by js, sometimes my loading fade out 1-2 sec before content is loaded. I can use js or jquery. For now, I used something like that :
$(window).on ('load', function (){
setTimeout(function (){
$("#loading").fadeOut('slow');}, 1000)});

Execute the function once you received data through AJAX. Check the code snippet below
$.ajax({
url: '/URL/TO/CODE',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //This is optional if you are using x-csrf-token validation of if u want to pass any header data
},
type: "post",
data: {
data:data //In case if you need to pass any data
},
dataType: 'json',
cache: false,
before:function(){
//Is you want to show any loader or anything while ajax is being executed.
},
success: function (response) {
//Once your ajax is success you can call your custom function to do things with the data
myCustomFunction();
},
error: function (res) {
console.log(res);
}
});
function myCustomFunction(){
//This to be executed when all data are filled by ajax and page is loaded
}
Hope this helps.

$(window).ready(function (){
setTimeout(function(){ $("#loading").fadeOut('slow'); }, 3000);
});

Related

Saving Variable in AJAX success call to pass in Another AJAX success call

Creating a 'refresh' button via jQuery, AJAX and PHP.
This particular one I'm having control two DOM instances (divs) - #sold-container, and also #totalorderswidget.
$(document).ready(function() {
$(function() {
$('#orderfeed').on('click', function() {
var orders;
$.ajax({
type: 'POST',
url: 'liveorderwidget.php',
beforeSend: function() {
$('#sold-container').html('<div class="page-loader"></div>');
$.ajax({
url: "totalorderswidget.php",
beforeSend: function() {
$('#totalorderswidget').html('<div class="page-loader"></div>');
},
success: function(orderdata) {
// $('#totalorderswidget').html(orderdata);
orders = orderdata;
}
});
},
success: function(solddata) {
$('#sold-container').html(solddata);
$('#totalorderswidget').html(orders);
}
})
});
});
});
I didn't like how each DIV was updating and showing my page-loader CSS at different times, so I thought I'd try and grab the data to pass and display them both at the same time (get data from the first ajax call, display both on the second).
This is working as two normal AJAX calls, and each appends the success html to each id on it's own. (uncommenting // $('#totalorderswidget').html(orderdata); works),
but initializing a variable like var orders; outside the functions and trying to put the data in the success call (orders = orderdata;) does not work.
Doing a console.log on the first AJAX success call (orderdata) brings back the expected response, but trying to use it in the second AJAX call ($('#totalorderswidget').html(orders);) does not work and a console.log brings back undefined for the order variable.
What must I change in order to grab data from the first success call function and bring this data into the second/final ajax success call?

setInterval() firing but ajax update div content not working

In the onDocumentReady(), $(function () {...}), I have a line: window.setInterval("readPluginCache();", 3000);
The readPluginCache() method invokes an ajax call to retrieve and format replacement html for a named $('#pluginCacheData') element.
I can see in Chrome (F12) that the ajax start, complete and success events are being recorded every three seconds (as expected).
However, the new html isn't replacing the old html values...
I have a button on the page (as a backup) and it calls the readPluginCache() method; it works!
How do I make the setInterval() methodology to work?
function readPluginCache() {
if (!isAuthorized) {
addMessageError("Error: Unauthorized readCache attempt.");
return false;
}
$('#pluginCacheData').hide();
$.ajax({
type: "POST",
url: infoPageName + "/BriskPluginCacheInfoHtml",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (response) {
$('#pluginCacheData').empty();
$('#pluginCacheData').append(response.d);
}).fail(function (jqXHR, exception) {
if (jqXHR.responseText.toLowerCase().indexOf('html') !== -1) {
addMessageError("Internal Server Error: readPluginCache(). Please check the event log.");
}
else
addMessageError("Error: " + jqXHR.responseJSON.Message);
alert(exception);
}).always(function () {
$('#pluginCacheData').show();
});
return true;
}
Okay, I got it working; but I'm not sure why this works...
I have abstracted the original ajax call by encapsulating it another function called readAll(), so: window.setInterval(readAll, 3000). The readAll() calls three different ajax-based html/div modifying methods sequentially. I did this b/c there are other parts of the page that also need to dynamically update... It's a mystery to me why this works when one ajax call didn't.

AJAX - Is there an on Data Receive Function?

I have a page that loads a lot of data from the database and writes it to the DOM.
Depending on the amount of records, this could take a good 30 seconds or so between receiving the data and printing it to the DOM.
I am curious if there is a way to detect once data has begun downloading / received from the AJAX call?
The reason I ask is I have a loading indicator (spinner gif) on the page that shows that something is happening.
I would like to be able to detect when data has begun downloading and change this to another message, kinda like "Step 2 of 2" so that the user knows it is progressing.
Step 1: On Document Ready, show loader: $('#loading').show();
Step 2: Trigger AJAX call to fetch data
$.ajax({
url: "api/fetchDashboard",
type: 'POST',
cache: false,
data: {
dashboardID: dashboardID
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
// Write data to the DOM here
// Once done, hide loader
$('#loading').hide();
}
});
Step 3: Write our data to the DOM and hide the loading indicator
My ask is that once we start receiving the data, detect that and change the loading indicator to something else to state that we have retrieved the data and its being prepared for viewing.
Is this possible to detect and trigger another function upon receiving? In the image above, you can see that it is downloading all the data and was thinking that once that counter started, it would be an indication that we have retrieved something back.
Update:
Per ask, this is how I am appending to the DOM, outside of the loop once all the rows have been concatenated.
var output = '',
$.ajax({
url: "api/fetchDashboardRender",
type: 'POST',
cache: false,
data: {
dashboardID: dashboardID
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
// Set our results as a variable
dashResults = data // Holds the dashboard results
// Loop over the core data
$(dashResults['data']['results']['data']).each(function() {
output += 'Table Row Data Here';
});
// Append the results to the DOM
$('[name=results]').empty().append(output);
}
});

Refresh a DIV on ajax success

I have a page with has a heading say :
<div class="something"><? some php code ?></div>
In that page I also have an ajax doing a job like:
<script>
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#loader").show();
}).ajaxStop(function () {
$("#loader").hide();
});
});
$('#link').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert("Added Succesfully");
}
});
return false;
});
</script>
Now in the success in ajax i also want to refresh the div i mentioned. Only refresh as it is attached to PHP which will fetch data from an external API. Is this possible ?
You could put your php code in an external file and reload your div by calling JQuery load method:
$("#something").load("mycode.php");
I hope it helps you.
link
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(JSON.stringify(data));
With the append function you can insert the data from the ajax call into a div. explanation and example
The append() method inserts specified content at the end of the selected elements.
Tip: To insert content at the beginning of the selected elements, use the prepend() method.
Or maybe this answer can fix your issue
or you can take a look at the jquery load function
Load data from the server and place the returned HTML into the matched element.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.

How can one trigger a function onchange of a div?

Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});

Categories

Resources