how to update content automatically without reloading webpage using php/ajax? - javascript

I'm trying to create an auction tool using PHP. The problem I'm having (and I appreciate its a basic one but I need clarification) is that I don't understand how to update the "auction price" automatically on each users screen without them having to take any action or without causing a full reload of the page.
So far I understand that Ajax is used to do this but if anyone could point me in the right direction or to any useful materials. My plan for my project so far is to use PHP and JavaScript so any solution would need to be compatible with these languages.
Note: I'm using a MySQL database.

Ther question you asked has so much possible answers, they could fill a whole book.
The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:
setInterval(function(){
$.get( "anyChanges.php", function( data ) {
//do something with the returned data. Maybe update a table or something
});
}, 3000);
On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.
Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.
The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first:
tutsplus tutorial
This library will be helpfull:
socketo.me

Php/Ajax example:
In this example you have index.html and record_count.php files
Here is the Code:
index.html contains the html code and javascript call to load record_count.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<body>
<div id="load_tweets"> </div>
</body>
and record_count.php has the php code
<?php
echo "some code or variable here";
?>
you can change the javascript interval to suit your needs
I'll leave you the blog link as a reference: 9lessons

As I making interactive displays, which must switch pages instantly, then I create pages without refreshing.
My approach is something like that:
I have one index.html with all structure (pages) with all necessary html tags.
javascript/typescript loads json from CMS (Kirby for example), which has all information about texts and image links.
when json is loaded now I just need to switch between pages by showing/hiding or creating/removing html elements. And all data and texts are loaded by javascript.
There is some cons, which can be fixed, for example link for each page in address bar. In that case You need to add history management and change url in address bar on page switch.

Related

How refresh page when a user insert a row into the database?

i'm doing a little group chat that every message are stored into the database. When a message is store the page need to refresh. how can i do a thing like this ?
You can use Web Sockets to keep open a connection to the server. You can use the ratchet library: http://socketo.me/ Check the documentation to have a overview of this module.
Also, you can check this page to have an overview of this revolutionary system http://www.html5rocks.com/es/tutorials/websockets/basics/
EDIT:
However, you can use AJAX, but make it simple with JQuery. Don't complicate your code ;)
Ajax is simple to use with JQuery. Don't make a Text area becouse it is ugly. Make a in your document and other in an appart document and call it using:
$.get("theotherpage.html", function(data){
$("#localdiv").html(data);
});
Give a look at this page teaching you to use JQuery AJAX: http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
You want to use AJAX. With AJAX you can refresh parts of the page, without refreshing the entire page.

Page Load alternative in a Pure HTML AJAX Website

I am working on a pure HTML website, all pages are HTML with no relation to any server side code.
Basically every request to the server is made using AJAX, I send data from forms, I process this data in Handlers, then I return a JSON string that will be processed back on the client side.
Let's say the page is loaded with parameters in the URL, something like question.html?id=1. Earlier, I used to read this query string on Page Load method, then read data from the database and so on...
Now, since its pure HTML pages, I'm trying to think of an approach that will allow me to do the same, I have an idea but its 99% a bad idea.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page. I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Is my goal impossible or there's a mature approach out there?
Is my goal impossible or there's a mature approach out there?
Lately there are a good handful of JavaScript frameworks designed around this very concept ("single page app") of having a page load up without any data pre-loaded in it, and accessing all of the data over AJAX. Some examples of such frameworks are AngularJS, Backbone.js, Ember.js, and Knockout. So no, this is not at all impossible. I recommend learning about these frameworks and others to find one that seems right for the site you are making.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page.
This sounds like a fine idea.
Here is an example of how you can use JavaScript to extract the query parameters from the current page's URL.
I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Here is why you should not worry about this:
A user's browser will generally cache the HTML file and associated JavaScript files, so the second time they visit your site, the browser will send requests to check whether the files have been modified. If not, the server will send back a short message simply saying that they have not been modified and the files will not need to be transmitted again.
The AJAX response will only contain the data that the page needs and none of the markup. So retrieving a page generated on the server would involve more data transfer than an approach that combines a cacheable .html file and an AJAX request.
So the total load time should be less even if you make two requests instead of one. If you are concerned that the user will see a page with no content while the AJAX data is loading, you can (a) have the page be completely blank while the data is loading (as long as it's not too slow, this should not be a problem), or (b) Throw up a splash screen to tell the user that the page is loading. Again, users should generally not have a problem with a small amount of load time at the beginning if the page is speedy after that.
I think you are overthinking it. I'd bet that the combined two calls that you are worried about are going to run in roughly the same amount of time as the single webforms page_load would if you coded otherwise - only difference now being that the initial page load is going to be really fast (because you are only loading a lightweight, html/css/images page with no slowdown for running any server code.
Common solution would be to then have a 'spinner' or some sort (an animated GIF) that gives the user an visual indication that the page isn't done loading while your ajax calls wait to complete.
Watch a typical page load done from almost any major website in any language, you are going to see many, many requests that make up a single page being loaded, wether it be pulling css/images from a CDN, js from a CDN, loading google analytics, advertisements from ad networks etc. Trying to get 100% of your page to load in a single call is not really a goal you should be worried about.
I don't think the 2-requests is a "bad idea" at all. In fact there is no other solution if you want to use only static HTML + AJAX (that is the moderm approach to web development since this allow to reuse AJAX request for other non-HTML clients like Android or iOS native apps). Also performance is very relative. If your client can cache the first static HTML it will be much faster compared to server-generated approach even if two requests are needed. Just use a network profiler to convince yourself.
What you can do if you don't want the user to notice any lag in the GUI is to use a generic script that shows a popup hiding/blocking all the full window (maybe with a "please wait") until the second request with the AJAX is received and a "data-received" (or similar) event is triggered in the AJAX callback.
EDIT:
I think that probably what you need is to convert your website into a webapp using a manifest to list "cacheable" static content. Then query your server only for dynamic (AJAX) data:
http://diveintohtml5.info/offline.html
(IE 10+ also support Webapp manifests)
Moderm browsers will read the manifest to know whether they need to reload static content or not. Using a webapp manifest will also allow to integrate your web site within the OS. For example, on Android it will be listed in the recent-task list (otherwise only your browser, not your app is shown) and the user can add a shorcut to the desktop.
So, you have static HTMLs and user server side code only in handlers? Why you can't have one ASP .Net page (generated on server side) to load initial data and all other data will be processed using AJAX requests?
if its possible to use any backed logic to determine what to load on server side, that will be easy to get the data.
say for example if you to load json a int he page cc.php by calling the page cc.php?json=a, you can determine from the PHP code to put a json into the page it self and use as object in your HTML page
if you are using query string to read and determine, what to load you have to make two calls.
The primary thing you appear to want is what is known as a router.
Since you seem to want to keep things fairly bare metal, the traditional answer would be Backbone.js. If you want even faster and leaner then the optimised Backbone fork ExoSkeleton might be just the ticket but it doesn't have the following that Backbone proper has. Certainly better than cooking your own thing.
There are some fine frameworks around, like Ember and Angular which have large user bases. I've been using Ember recently for a fairly complex application as it has a very sophisticated router, but based on my experiences I'm more aligned with the architecture available today in React/Flux (not just React but the architectural pattern of Flux).
React/Flux with one of the add-on router components will take you very far (Facebook/Instrgram) and in my view offers a superior architecture for web applications than traditional MVC; it is currently the fastest framework for updating the DOM and also allows isomorphic applications (run on both client and server). This represents the so called "holy grail" of web apps as it sends the initial rendered page from the server and avoids any delays due to framework loading, subsequent interactions then use ajax.
Above all, checkout some of the frameworks and find what works best for you. You may find some value comparing framework implementations over at TodoMVC but in my view the Todo app is far too simple and contrived to really show how the different frameworks shine.
My own evolution has been jQuery -> Backbone -> Backbone + Marionette -> Ember -> React/Flux so don't expect to get a good handle on what matters most to you until you have used a few frameworks in anger.
The main issue is from a UX / UI point of view.
Once you get your data from the server (in Ajax) after the page has been loaded - you'll get a "flickering" behavior, once the data is injected into the page.
You can solve this by presenting the page only after the data has arrived, OR use a pre-loader of some kind - to let the user know that the page is still getting its data, but then you'll have a performance issue as you already mentioned.
The ideal solution in this case is to get the "basic" data that the page needs (on the first request to the server), and manipulate it via the client - thus ease-in the "flickering" behavior.
It's the consideration between performance and "flickering" / pre-loading indication.
The most popular library for this SPA (Single Page Application) page - is angularJS
If I understand your inquiry correctly. You might want to look more about:
1) window.location.hash
Instead of using the "?", you can make use of the "#" to manipulate your page based on query string.
Reference: How to change the querystring on the same page without postback
2) hashchange event
This event fires whenever there's a changed in the fragment/hash("#") of the url. Also, you might want to track the hash to compare between the previous hash value and the current hash value.
e.g.
$(window).on('hashchange', function () {
//your manipulation for query string goes here...
prevHash = location.hash;
});
var prevHash = location.hash; //For tracking the previous hash.
Reference: On - window.location.hash - Change?
3) For client-side entry-point or similar to server-side PageLoad, you may make use of this,
e.g.
/* Appends a method - to be called after the page(from server) has been loaded. */
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
function YourPage_PageLoad()
{
//your code goes here...
}
//Client entry-point
addLoadEvent(YourPage_PageLoad);
Since you're doing pure ajax, the benefit of this technique is you would be able to easily handle the previous/next button click events from the browser and present the proper data/page to the user.
I would prefer AngularJS. This will be a good technology and you can do pagination with one HTML. So i think this will be good framework for you as your using static content.
In AngularJS MVC concept is there please read the AngularJS Tutorial. So this framework will be worth for your new project. Happy coding

number of reading text in web page with javascript

how to found how many times a news(for example)are read in website?
<p> <!-- my news--></p>
var counter=0;
windows.onload=function() {
counter++;
}
You can't use a JavaScript variable to hold your counter. Each time your page loads this variable is reset to 0.
You need to store the information somewhere, such as a database or in a file on the server. You can't store information like this inside your code.
Look into MySQL databases and PHP.
Your own server's logs can tell you how many times a page has been loaded, and that's a far easier approach than using JavaScript. If you absolutely have to use JavaScript, you'll need to use Ajax (or something) to communicate the result to the server.
Really, Google Analytics is the right tool for this job.

Pull an external page 10 seconds after the request using PHP

I have two web pages that I'll call domain.com/Alvin and domain.com/Bert for this example.
Alvin displays search results based on a query string variable, but it loads the results using JavaScript approximately two seconds after the page loads.
Bert needs to use these results for occasional ad-hoc reporting, but due to the way the company is set up, I can't link directly into the database that Alvin is pulling from. A different team manages the Alvin page, so I won't have access to change their existing code.
While I think I could do this with .NET, I'm unsure of how to do the request with PHP which is highly preferred for the page.
Is anybody aware of how I could use file_get_contents, file_get_html or any other PHP functions to get the HTML of another page but only pull the HTML five seconds after the initial request to allow the JavaScript to update the results?
Credit to mplungjan - not sure why I didn't think of this earlier, but I was able to replicate the AJAX to the same request. Thanks!
Since they are on the same domain, one page can ajax the other page in – mplungjan

Javascript function execution on link click?

I have a link, that when a user clicks on it, it loads a different page as normal but also executes a JS function that autofills a specific text-box on that different page. Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
You can't do this from the source page.
It's a security feature. Imagine if you wrote a JS function that went to an online banking page and auto-filled a bank transfer using the user's current cookie. That's why you can't.
If you control the other page then the sequence you can use is:
Save data to the server;
Go to the new page with a JS redirect;
The new page is loaded from the server;
While loading th epage the data that was saved from the server is retrieved and used to populate the text box.
So it can be done from the server but only if you save it there. The only way of doing that is using Ajax.
An alternative approach is:
Instead of a JS redirect, submit the page back to the server;
The server saves whatever data it needs to;
The server sends back an HTTP redirect to the new page;
The new page uses the saved data to construct the new page with the populated text box.
At the end of the script add return false;. This will make the page run the script without redirecting the page.
Edit: (after saw your edition).
Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
jQuery is a javascript library, this it doesn't matter if you use plain javascript or use jquery as long as you happy with the result.
And about what you say that you successfully manipulated a page fro the redirecter page... I don't see how it possible.

Categories

Resources