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);
}
});
Related
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);
});
I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}
I have a java servlet which responds with a number in text/plain format. What I want to do is have another page run a script which polls this URL and triggers an alert window when the number there has changed from the first time it was loaded. I have little to no experience with javascript and so far have been unable to follow any of the long-polling tutorials I have found.
Basically, I need to start the poll on page load, remember what the first value retrieved was, and then trigger an alert window once the value changes.
This is what I have so far, however I believe I need to parse the data somehow. The URL returns a text/plain page with a number on it. That's it.
var initial = null;
function checkForMsg() {
$.ajax({
type: "GET",
url: URL_GOES_HERE,
dataType : "text",
async: true,
cache: false,
success: function(data) {
if (initial == null) {
initial = data
}
else if (initial != data) {
alert(data);
}
setTimeout('checkForMsg()', 12000);
},
error: function() {
setTimeout('checkForMsg()', 12000);
}
})
}
$(document).ready(function(){
checkForMsg();
});
I have links in a JQuery DataTable that use JQuery UI's tooltip feature. Each link has a tooltip that is populated by an Ajax call. I would like to limit the number of Ajax calls to as few as possible. The DataTable uses server-side processing, and the results are paginated, so there will never be more than ten links on the page at any one time.
The data that is returned by the Ajax call will never change and thus can be safely cached. In my testing, I have seen that the browser does cache the result of each Ajax call, so that it only makes one call per link, and then uses the cache thereafter. My concern is that some user might have their browser configured in such a way that it doesn't use the cache for some reason, and they will be firing off one Ajax call after another, every time they mouse over a link.
Here is the JavaScript for the tooltip:
$('.jobId').tooltip({
content: function(callback) {
var jobId = $(this).text();
$.ajax({
url: 'myUrl',
data: {jobId: jobId},
dataType: 'json',
success: function(data) {
var html = formatResults(data);
callback(html);
},
error: function() {
callback('An error has occurred.');
}
});
}
});
I considered storing the result of each Ajax call in a JavaScript object declared at global scope, and then checking that before making the Ajax call, but I have the vague sense that this might cause a memory leak somehow.
var gJobs = new Object();
$('.jobId').tooltip({
content: function(callback) {
var jobId = $(this).text();
if (gJobs[jobId]) {
callback(gJobs[jobId]);
} else {
$.ajax({
url: 'myUrl',
data: {jobId: jobId},
dataType: 'json',
success: function(data) {
var html = formatResults(data);
gJobs[jobId] = html;
callback(html);
},
error: function() {
callback('An error has occurred.');
}
});
}
}
});
I am also concerned that if the table has a large number of rows, the gJobs object could end up using a lot of memory. To prevent the gJobs object from growing indefinitely, every time the user goes to the next or previous page of results in the DataTable, I use the fnDrawCallback function to reinitialize gJobs:
$('#jobsTable').dataTable({
...
"fnDrawCallback": function() {
gJobs = new Object();
}
});
I should mention that since the data returned by each Ajax call doesn't change, I could also just store the data in the JSP as static text, and populate the tooltips that way instead of using Ajax. However, I have to make a separate web service call to get the data for each link, and rather than make ten web service calls every time the user pages forward or back, I would rather load the data on demand via Ajax.
Is there anything wrong with this approach? Is there any way this can cause a memory leak? Should I explicitly delete all the properties of gJobs before reinitializing it? Thanks for your help.
Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex
AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz
agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});