How to prevent requests to server every page load - javascript

I wanted to know if there is a way to stop Javascript from calling a php every page and populating an array, and instead just carry the array accross all the pages the user browsers.
Currently every page load it makes a new reqest to the server and repopulates the array for example when a user clicks link on a html page.
This is what i have in my JS file:
//Browser Support Code
function call_data(url,data){
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
querystring = "?dta="+data;
AJAX.open("GET", url + querystring, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var statistics = JSON.parse(call_data('user_info.php',userid));//user data
I don't currently see an advantage if its calling every page load, as I might as well do without ... unless theres a way to keep my array set each page load?

You should use HTML5 Local Storage.

You could use the Web Storage / DOM Storage API through JavaScript. It has decent browser support and if you implement it properly you can always fall through to requesting the PHP page if Web Storage is not available.
Here is a tutorial to get you started:
http://www.diveintojavascript.com/tutorials/web-storage-tutorial-creating-an-address-book-application

You can store it in a cookie and check if the value in the cookie is valid, load it from cookie, otherwise request it from the server and save it in the cookie for future use.

Related

Make window.location.href load page from Server instead from browser cache

I am making a redirect using window.location.href to Listing view after an Item is added to DB after successful CREATE operation.
But what it does, it simply fetches old page (not showing the newly added item) that was previously in borwser's cache.
I want it to fetch every think from server, just like we use true parameter in document.location.reload(true) to load a fresh copy of page from server.
You can use this:
window.location.href = "http://www.mywebsite.com/products?t="+ (new Date().getTime());
Or:
window.location.href = "http://www.mywebsite.com/products?t="+ Math.random();

Automatically Enable Submit button at particular time from server using PHP JS

What I'm looking for is this.
I have a simple PHP page with a submit button that is disabled by default.
I want the submit button to be enabled at a particular time for example 02:00:00
With PHP i can get the time from server with date("h:i:s") which i am using in a JS variable.
like
var time = "<? php echo date("h:i:s") ; ?>" ;
Now by using setInterval() method every millisec i am trying to compare the value of "time" variable with the
particular time i want the button to be enabled.
like if(time=="02:00:00")
{
button.disabled=false;
}
But the problem is "time" variable should also dynamically change to meet the conditions otherwise nothing will happen.I can't get any simple solution.Do i require AJAX for this?
Any help will be appreciated :)
Thanx!
I would update the time variable using JavaScript:
var curTime = new Date();
var firstColon = curTime.toString().indexOf(":");
time = curTime.toString().substring(firstColon-2, firstColon+6)
I'm a Python person, but I think PHP servers work similarly in that when going to a link, a GET request is sent, and then data is sent back, possibly a dynamically created webpage with Python code, but that webpage can't contain any Python or PHP. Those languages are strictly server-side. You could send a request to the server to get the time, but that would be really inefficient and it's better to do this client side then constantly dynamically change the webpage with requests to your PHP server.
Since this is about disabling a button, if the button sends a request to the server, remember to check that the time is right server-side just in case someone tampered with the webpage using their JavaScript console client-side.
Isn't this enable/disable done better at server side? Why do you need to enable the submit button in JavaScript at all? Will it be too bad of a solution to simply inform the user that they cannot submit operation is not available at the moment? They can always refresh the page or come back later to see if it is enabled.
Alternatively, you can simply have an ajax request that periodically pings the server to see if the button can be enabled or not. But know that a savvy user can use Web Inspector tools available in modern browsers to change DOM state. Always validate your operations at the server side. Hope this helps.
Try the following
/* ########## HTML file ######### */
<html>
<head>
</head>
<body onload="timer_function();">
<button type="submit" id="validateIt" style="none">Submit</button>
</body>
<script type="text/javascript">
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//document.getElementById("msg").innerHTML=httpxml.responseText;
//document.getElementById("msg").style.background='#f1f1f1';
}
if(httpxml.responseText == "02:00:00")
{
document.getElementById('validateIt').style.display = 'block';
}
if(httpxml.responseText >= "00:00:00" && httpxml.responseText < "02:00:00"
|| httpxml.responseText >= "02:05:00" && httpxml.responseText < "02:00:00")
{
document.getElementById('validateIt').style.display = 'none';
}
}
var url="server-clock-ckk.php";
url=url+"?sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
tt=timer_function();
}
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
} // Display server time ends
</script>
</html>
/* ########## PHP file server-clock-ckk.php ######### */
<?Php
echo date("H:i:s", time());
?>

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

How can I take common large chunks of oft-reused HTML source code?

A slew of pages I've written for one of my web projects share some 144 identical lines of code, reproduced in each file. If I update one of those lines, I have to go back through ALL of the pages that share the code and update for each page. Is there a straightforward way to include HTML from a separate file?
And for bonus points, since so many pages use this code, it would be nice not to have to reload it for each page. Is there an easy way to store it in the browser's cache or only load the "content" section of the pages while leaving the rest of the page static?
Fountains of Thanks for any wisdom on this.
Mike
To include HTML from a separate file, use SSI (Server-Side Includes). This requires SSI support to be installed on the server, however.
You would write something like this in your files:
<!--#include file="included.html" -->
and that would include the file included.html when the page is accessed.
To load only the content of each page, use the XMLHTTPRequest object from JavaScript:
function LoadContent(url)
{
if (typeof(XMLHttpRequest) == "undefined")
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
// fallback for browsers without XMLHttpRequest
window.location.href = "no-ajax.php?url="+escape(url);
return;
}
}
}
else
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", url, false); // this request will be synchronous (will pause the script)
xmlhttp.send();
if(xmlhttp.status > 399) // 1xx, 2xx and 3xx status codes are not errors
{
// put error handling here
}
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
If we're assuming that you're talking straight html pages, with no server code (asp.net, php, or server side include ability), then in order to do both the including and the caching, you're going to need to use an iframe.
Each of your pages that duplicate the 144 lines of content should replace it with an iframe like so:
<iframe src="pagewithcontent.html"></iframe>
pagewithcontent.html would obviously be where you move the content to. The browser will cache the page appropriately, so that each parent page will simply get the shared content without making another request.
There's an article here that goes into great depth about html includes, and some javascript methods of doing it. I would strongly recommend against the javascript methods.
My answer reflects the assumption that you can't do anything on the server side. However, by far the best solution is to do so if you can.

Ajax call from Bookmarklet

I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.
I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?
Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?
You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.
If I've understand well your needs, that should be ok for your problem.
var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
I don't know if POST would work.
You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.
You will have to return JSON style data.
See: http://docs.jquery.com/Ajax/jQuery.getJSON
Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.

Categories