Dynamic webpage retrieves data from database slowly - javascript

I'm making a dynamic webpage which retrieves lots of data from a database very frequently, like at least every 3 seconds.
I tested my webpage and database locally by using XAMPP. It works perfectly. However, it turns to be very slow after I upload everything to 000webhost (my free account). My webpage even freezes (I cannot scroll the page, not even doing anything but wait for the data to be transferred.) when retrieving the data.
I used a setTimeout function which called several ajax commands to read data from my database. I have optimised the data capacity already, but the page still freezes. I also tried to disable most of the ajax commands and only left one. When loading, the page freezes just as a blink, but anyhow it still freezes...
Most of my ajax commands are like below which simply retrieves data from my database and updates the related fields on my webpage. Some ajax commands uses $.parseJSON() because I need the whole row from a table.
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
async:false,
success: function(response){
document.getElementById('balance').innerHTML = response;
}
});
Can anyone provide some suggestions how to solve this issue? Should I pay and get a better account?
Thanks.

to have an ajax refreshing every 3 s, your javascript & ajax must be like this:
function get_data(){
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
success: function(response){
document.getElementById('balance').innerHTML = response;
setTimeout(get_data(),3000);
}
});
}
get_data();
Put setTimeout() function inside the ajax. You will not get freeze because we don't set async as false

Related

Extend the time of an AJAX request

I have a function on the server to create hundreds of elements and store them in the database. This action takes time on the server and when the action finalize, it returns the result. The problem is that Ajax terminates the request after around 150000ms with Bad Request 400 and the runningProcess response.
The Ajax call is:
showProgressCursor();
$.ajax({
type: "POST",
url: strUrl,
data: {accountId: byId("account-id").value},
dataType: "JSON",
success: function (oResult, strTextStatus, internalResponse) {
console.log("Success")
_showTheResult(oResult, strTextStatus, internalResponse, allDataError);
hideProgressCursor();
},
error: function(oResult) {
manageError(oResult);
console.log(oResult);
hideProgressCursor();
}
});
Do you know how I can increase this time or cancel it until Ajax receives an answer?
Extra: at the moment, I am showing a loading wheel but it would be better if I show a bar with the progress of the operation, could I show something like that? (I have thought of making a different recurring request (every second for example) and obtaining the total created and the total to be created and thus be able to have the progress. I don't know if this is a good solution)

How to call a Javascript function inside a Jade/Pug file

I have a node.js project with frontend written in Pug. On the pug side I have written a Javascript function that is making an Ajax call and returning a string, I am trying to call this function inside that same pug file but it gives me a function not defined error. Can anyone please help with this?
header(class="global-header")
p Current Status: #{getCurrentAvail()}
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data){
console.log("===1")
currentAvail = data.message
console.log(currentAvail)
return data.message
},
error: function(data){
console.log("Error function avail");
}
});
}```
It appears you have some piece of external data and you want that data to show in a rendered web page. You have two basic choices here:
1. Server-side fetching and rendering of the data. You can have your server get the data before rendering the page and pass that data to your template engine so your template engine can insert the data into the page at the appropriate place.
2. Client-side fetching and insertion of the data. You can call the getCurrentAvail() function from within a <script> tag in the web page. This will send the rendered web page to the browser. As it loads, the browser will then execute your script, fetch the data from your server and then you would use DOM APIs in the browser to insert the result of that ajax call into the web page to make it visible to the user in the page.
Also, please note that your function getCurrentAvail() has no return value at all. You aren't returning anything from the outer function. Your return data.message is inside the asynchronous success callback so that just go back to nowhere. If you're going to go with the client-side option #2, then you can just put the DOM manipulation code right into the success callback function.
Your current code is attempting to do 1/2 server and 1/2 client and that is not something that will work.
At all times, have total clarity on what is in the server and what is in the client. Ajax methods run in the browser. A #{variable} construct exists only in Pug, and the substitution occurs on the server.
I think this is what you need:
header(class="global-header")
p Current Status:
span#status
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
document.getElementById("status").innerText = data.message
},
error: function(data){
console.log("Error function avail");
}
});
}
getCurrentAvail();

Efficient way of passing data and calling background script in PHP

I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

How to download a text file and store as a string in jQuery

I have a set of text files representing a table of data from a third party that I'd like to download using a JavaScript application. They look something like this:
col1 col2 .. coln
vala valb .. valz
valA valB .. valZ
etc..
I've been trying to use jQuery to do this. I've been able to use $.load, but I don't want to store the data in the DOM, instead I'd like to parse it out into an object. Whenever I try to use an of the ajaxy methods I'm getting an error I don't understand. For example:
var myData;
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: function(data) {
myData = data;
}
});
alert(myData);
Gives me an undefined value for myData. Any suggestions would be appreciated.
For that code to work the event needs to be syncrounus, in other word, set async: false in the $.ajax-call. The problem comes because ajax is normally async, meaning that when you do the alert, the request might, or might not have finished. Normally though, it won't cause it takes longer time to fetch a page than to do a function-call. So, by setting async: false, you tell jquery (and the ajax-handler) to wait till the page is finished loaded before you try to alert the data. Another method to achieve the same effect is to do something like this:
var myData;
function fin(data) {
myData = data;
alert(myData);
}
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: fin
});
This approach is probably better than to set async to false, because it won't make the browser hang while waiting for the page your loading. However, asynchronous programming is not something that is easy to learn, therefore many will find it easier to use async: false.

Categories