I have a button on my site, that when pressed sets the corresponding value in an JSON file to either 0 or 1. A function is continuously running and updating the color of the button depending of the JSON file. This is needed so the button has the same state on all devices.
Now my Problem: It is slow. I want it to be instantly on at least the device the button is clicked. I tried it by setting the color at the same time as the JSON file is updated, but this is buggy since the Ajax call takes some time and the button sometimes flickers. I made the following test: Every time the getStatus() function was called it would add either 1 or 0 to a div. I noticed that after the JSON changed it would still print out the old state a few times before printing the correct one, eventhought i turned cache off
Is there a way to make it faster? Here is the code:
Inex.html:
function getStatus() {
$.ajax({
url: 'status.json',
dataType: 'json',
cache: 'false',
success: function(data) {
varstatus = data;
setColor();
getStatus();
}
})
}
Index.php
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString);
$data[$_GET['id']] = "$f";
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
Another problem I have is that the page is not alway working at the first time. I have to reload to make the updates show, but then it works without.
Or is there another way to do this, without continuously downloading the file?
Related
$(function() {
var $items = $('#items');
$.ajax({
type: "GET",
url: 'some-url',
data: {},
success: function(items) {
$.each(items, function(i, item){
item_polys.push(item.polygon);
$items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
});
localStorage.setItem('item_polys', JSON.stringify(item_polys));
},
// Error handling
error: function (error) {
console.log(`Error ${error}`);
},
});
I need 'item_polys' to be saved into local storage before my corresponding html page loads. I would also settle for a way to reload the html page just one time each time after it loads, so that it will populate correctly. Thanks (and sorry if this has been answered already, I couldn't quite find what I was looking for when I searched)
Since you want the ajax request to occur when the user is on the exact same page that the populated elements will be in, I think the only good way of doing this would be to create or display the elements of the page dynamically. (This might be as simple as toggling a display: none on and off, but it depends on what the page is like and what you want.)
So, make a function like populatePage that shows the page, where the default state of the page is a loading screen (or blank, or whatever you want the user to see when the request is in progress). Maybe something like
const populatePage = () => {
const items = JSON.parse(localStorage.items);
for (const item of items) {
$items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
}
$('main').show();
};
where main is the container you want to show when things are ready, and that has styling that hides it by default. Then:
On pageload, check if the item exists in storage. If so, use it, and call populatePage immediately. Otherwise, have the page keep showing the loading banner or blank screen, make the ajax request, and call populatePage when it's finished.
$.ajax({
// ...
success: function (items) {
localStorage.items = JSON.stringify(items);
populatePage();
I have a query which returns a huge set of data (json). This takes far to long to present the grid to the user. So what I want to do is fire the initial query with a filter (say the records of the current year) and let the grid be build.
The grid is presented to the user and he can start working.
Meanwhile I fire a second query (in the background) to get all the other records (everything except the current year).
Now I want to add those records to the already existing grid. Without the user noticing.
Is this possible?
I think JSgrid and JQgrid behave the same but I use JSGrid
Thanks, Mike
In case of Guriddo jqGrid you can first load small portion of data and then using grid complete event set the datatype to local, load all the data put it into the data parameter and refresh the indexes. The loaded variable is used to prevent repeated loading in case of sorting pagging and etc - i.e the code is executed only once
Bellow the code and demo
var loaded = false;
$(document).ready(function () {
$("#jqGrid").jqGrid({
// url to load initially 10 records
url: 'grid.php',
datatype: "json",
....
gridComplete : function() {
// if the all the data is not loaded
if(!loaded) {
// set the datatype to local
this.p.datatype='local';
var ts = this;
$.ajax({
"url": "grid.php",
"dataType" : "json",
// instruct the server to get all the data with the same sortining
"data" : { oper: 'grid', page:1, totalrows : -1, sidx : 'CustomerID', sord : 'asc' },
success :function( resp ) {
// when loaded simple attach the response data to data array
ts.p.data = resp.rows;
// refresh the indexes
ts.refreshIndex();
// mark that the data is loaded in order no to do it again
loaded = true;
}
});
}
}
});
Just set a delay timer on your function. I am not to sure if user wouldn't notice the changes though. But that's a good starting point i guess.
Here is an example on how to use setTimeout();
This will allow your function to be executed after a certain time. So when an user loads up the table and start working. You will fire the other function(after certain amount of time) that repopulates the table. I am not to sure how your table is populated so not to sure if the execution will be invisible to the user.
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);`
I have following dropdown which calls javascript showTable method.
<select name="any_name" id="any_id" onChange="showTable()">
I have following showTable method which calls a php method via post to populate data in my showData div.
function showTable()
{
$.ajax({
type: "POST",
url: "sample.php",
data: {"Id" : myId},
success: function (data)
{
document.getElementById("showData").innerHTML= data;
}
});
}
It works fine. Now the problem arises when I hit FORWARD and then BACKWARD browser button. On hitting BACKWARD button, I get my previous page but my showData div is empty. How can I retain data in this div which I got from my PHP script? I think I have made it clear what I want to ask.
Look for local storage w3schools.com/html/html5_webstorage.asp and manage to save and retreive values between your back/forward behavior.
;)
i have script that works as follows:
there is main page with 'start' button that initializes javascript function which loads a php page into a div frame, then via setTimeout it calls a 'refresh' function thats supposed to work indefinitelly and refresh the page inside frame
the refreesh timer is in database and is forwarded to java like this:
var min_refresh_time = ;
$min_refresh_time_sec is taken from database earlier in the code
what i wanted to modify is so the refresh min_refresh_time would be taken each time a refresh function is run, to my surprise this worked (or at least i thought so):
var min_refresh_time = ;
(custom sql functions are defined in separate php file included in main.php which is my main page)
unfortunatelly it seems that it 'worked' only due to some strange caching on java part and my pseudo-php code to take value from database is just a hoax - it looks like it is run only initially and then stores output somehow
simplified code of what is done and what i want to do:
function refresh_code(){
refresh_time = <?php Print(sql_result(sql_execute("SELECT value FROM settings WHERE setting='min_refresh_time'", $connection), 0, 0)); ?>;
refresh_time = 5;
alert(refresh_time);
$.post("index.php",{refresh_time:refresh_time_post, account_group: "1"},
function(data)
{
$.ajaxSetup ({
cache: false,
});
$("#frame_1").html(data);
});
setTimeout(function(){refresh_code()}, refresh_time);}
lets say min_refresh_time is 1 in database, i run it, it alerts 1 then 5 each time it self-refreshes, now if i go to database and change 1 to 3 i would want it to alert 3 then 5 obvious, it still does 1 then 5 tho...
i need a way to execute a dummy php file that only takes value from database, then sends it via post back to java and it gets intercepted there, any simple way to do that?
or do i need to use entirely different method for retrieving database value without js...
thx in advance
update:
i actually came back to it and analyzed potential solutions with fresh mind
first of all, i dont think my initial code had chance to work, java cant execute serverside code by itself, i took some of my aax code from other script and reworked it to launch php file that grabs the value from database, then i intercept output data and put into variable
looks like that:
$.ajax({
method: "POST",
url: "retrieve_refresh.php",
data: { retrieve_data: "max"},
cache: false,
timeout: 5000,
async: false,
cache: false,
error: function(){
return true;
},
success: function(msg){
if (parseFloat(msg)){
return false;
}
else {
return true;
}
}
}).done(function(php_output2) {
max_refresh_time = php_output2;
});
retrieve_refresh.php returns only the variable i want but the solution is unelegant to say the least, i havent searched yet but could use a way of sending variables as post back to ajax...
It was suggested that I try to explain my problem with no code so here it goes. I have a webpage that lists a bunch of links with project names as seen in this jsfiddle. What I want to do next is display a second webpage after a project link is clicked by a user. The second webpage would need to make a second ajax request like in this Second page jsfiddle to get new information to display a project summary, citations and names for that particular project. The part that's killing me is the ajax request for the second page currently has a number 504216b6e4b04b508bfd333b in the url which means it will only use that project for the second page to display summary, citations and names. I need that ajax request to take a variable for any id number. However to compound the problem the id number comes from a user clicking a link on the first page. So my problem is getting the value of the id once a link is clicked and putting it into the ajax request for the next page. I have all the work done for what the pages will display but I can't get the value from the one file to the next. Any help is appreciated, Thanks.
wouldn't let me save without putting some code so this is just the bare bones,
// The ajax request is in another file but it works good
promise.done(function (json) {
// Make some links
// Which link was clicked? I need to see some id please
$('#sbItems a').on('click', function (e) {
e.preventDefault();
// Do stuff to find the id for the link the user clicked
// Assign the id to a variable that I can use in the next ajax request
// that is called in a seperate file
testId = json.items[itemId].id;
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
second file has,
// Need to somehow, someway get the testId variable that holds the id
// into this file
var url = 'https://www.sciencebase.gov/catalog/item/ + THE TESTID + ?format=
jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
complete: onComplete,
success: function(json) {
// Display some stuff based off this url
}
});
If you're trying to get a number from the first page and into the second page when you click a link that takes you to the second page so you can use it in the second page ajax call, then there are several options:
Attach the value onto the URL when requesting the second page as a search parameter like this: http://www.sample.com/mypage?id=504216b6e4b04b508bfd333b. The in the second page, parse that id value out of the URL and use it for your ajax call. This is the safest of these three options because it works properly even if the user has multiple windows open clicking on different pages in your site.
When clicking on the link in the first page, store the id value as a cookie. In the second page, retrieve the id from the cookie.
Same as option 2, but store the value in local storage.