Refresh Using Ajax/PHP - php

Further to my question yesterday (here), I am working on a webpage that has a section that shows 'live' order details.
The top half of my webpage has Spry Tabbed Panels. One of the panels contains an include call to a separate php page that I have created (getOpenOrders.php). This contains an SQL query to obtain all open orders and then puts the details into a table.
As a result, the table of open orders is shown in the Spry panel. What steps do I now need to take to have this refresh every 15 seconds?

Do you really want to call the database every 15 seconds for each user? isn't that an overload?
I'm not saying that your database will be overloaded, but, thats how you shouldn't do things!
Edited
you should show an image, or the link to that page in order to gt an appropriate answer, because it all depends in what are you doing in the table.
because I don't know, I will give you an answer on what probably is happening.
Because you said that you're new to the ajax world, let's make things simple, and not to complicate on the you should return a JSON object and use it to re populate your table. :)
So we will start with 2 buttons (Previous and Next) so the user can move the data that is showing (you probably don't want to give him/her 100 lines to see right?)
let's say that you have 2 pages, a showData.php and getTable.php, in the showData.php you will need to load jQuery (wonderful for this) and add a little code, but where the table is to be placed, just add a div tag with an id="myTable" because we will get the data from the getTable.php file.
getTable.php file has to output only the table html code with all the data in, without no html, body, etc... the idea is to add inside the div called myTable all the code generated by getTable.php
Let's imagine that getTable.php gets a page variable in the queryString, that will tell what page you should show (to use LIMIT in your MySQL or PostgreSQL database)
You can use jQuery plugin called datatables witch is one of my choices, check his example and how small code you need to write! just using jQuery and Datatables plugin.
The first description follows the jQuery.Load() to load the getTable.php and add as a child of the div and wold do this for the previous and next buttons, passing a querystring with the page that the user requested. It's to simple and you can see the website for that, if you prefer to use the DataTables plugin, then just follow their examples :)
if you, after all this need help, drop me a line.

<META HTTP-EQUIV=Refresh CONTENT="15; URL=<?php print $PHP_SELF ?>">
This should be in between the head tags.
-or-
header('Refresh: 15');
This should be before the head tag and directly after the html tag.
As said by balexandre, a different method should be used. One that does not require a database hit every 15 seconds for every single user that is connected to the site. But, there is your answer anyways.

Although, balexandre makes a very good point, if you do decide that you need a refresh, you could simply do something like this in your JavaScript:
window.onload = function( )
{
setTimeout( 'window.location.refresh( )', 1500 );
}
(I've not tested the above code, so syntax may need to be tweaked a little, but you get the idea)

Related

How do I get an element to appear once it has been selected from a dropdown menu?

I have a dropdown menu that has school subjects listed. I also have a countdown timer for each subjects test date (many subjects share a date). I want to make it so that when the user selects the subject, the right countdown timer appears without the page refreshing.
Right now I have this working using PHP: I have 9 different countdown timer made in JavaScript (I used this tutorial from w3schools) and 9 separate PHP files like this:
$newSubject = $_GET["chooseSubject"];
if ($newSubject == "Math" OR $newSubject == "Chemistry") {
echo '<p id="subjectSet1"></p>';
echo '<p class="dates">October 16. 2019 klo 9:00</p>';
}
I have a button that redirects to a page that then shows the correct countdown timer.
However, I'm looking to achieve something like this:
https://yle.fi/aihe/artikkeli/2019/05/15/ylioppilaskokeiden-pisterajat-kevat-2019
Under the "Ylioppilaskokeiden pisterajat, kevät 2019" there is a select menu, and when you choose a subject it automatically shows the correct table.
This is where project design comes into play. If you expect your dropdown set to be small, you can simply render all of the content on page-load and then use JS/CSS to show/hide each block of content on change of the dropdown.
Alternatively, if you are expecting a larger dataset this could potentially affect your page load times and also make it longer for the browser to render the data (even when it is in a hidden element). In this situation I would look into using AJAX and load in content when you click on a section instead. This is slightly more complex but is;
A good learning exercise
More efficient in the long-term
EDIT:
If you're wanting to go down the show/hide route. This is simple enough using jQuery. There are a few options you could take however I would suggest toggle as a start - see docs here
For AJAX, this will take a bit more reading into. I would also suggest using jQuery's ajax function - see docs here

how to limit the content to be shown on a page?

I'm making a page which shows data, which is quite enormous.Tried pagination on it but didn't work the way I wanted. I'm looking for, something like "See more results", which on clicking will increase size of the page. Further, is it possible to do it with some limit on content to be shown on every click, like on every click it should show, say 10 or 15 rows ?
The best way to do this, in my opinion, is to cut the text and load just part of it with PHP. In this way the initial page won't be heavy. Then with a ‘Read more...’ button you can send an ajax request (with jQuery, maybe using the function load() function) you can get additional text, which will be appended in a div after the current text. Additionally, if you want to retrieve just some lines each time you press the button, you can check with jQuery how many div are already added (just adding a class to your new divs, you can check this just with $('#NameOfTheparent div.classOfTheNewDivs').length) and pass the variable to PHP, during the ajax request (so it won't be $('newDiv').load('something.php') but $('newDiv').load('something.php?var=numberOfDivAlreadyLoaded').
Well, this is the concept. :P
in my opinion, you need something like this:
http://andylangton.co.uk/articles/javascript/jquery-show-hide-multiple-elements/

OnHover run php script

Okay I'm not really sure how to approach this. I have a user-generated post board where people post, it drops down onto a list of a bunch of posts. When you click on the ID number of the post it will bring you to a separate page with just that post and the comments on the post. I want it so when you hover over the href it drops down something that tells the user there are x amount of comments on this post. This way people know if there is comments without switching pages and also being able to be able to click the href still and go to the postid page.
I assume some ajax/jquery/javascript would be used to accomplish this but since I'm fairly new to ajax and jquery I'm not certain how this would be done. Thank you!
For a hover effect, it would be better if that information was already stored on the page and just hidden. Then when the user does hover, you can just un-hide it and have it positioned where you want, and then hide it again when their mouse leaves the area. Using AJAX requests for this purpose would waste away a lot of HTTP requests for such a tiny amount of information.
Really, you could do the hover effect using pure CSS if you wanted too (I would).
Since a hover happens fairly often, I wouldn't use it as the default event to fire an AJAX-request. This would increase the HTTP-traffic enormous. See if you can fetch this information when the page is build (and put it in then) or use something else like a "preview"-button for the event.
Anyways, this would be the basic workflow if you want/need to use AJAX:
Write a PHP-script (or any other language you use) which fetches the number of comments (and what else you want to display) from the database (or where your data is stored).
This script should then be called via AJAX (with $.ajax() from jQuery for example). As the expected return-type you would then use json.
The script which fetches your data would then create an object, use PHP's json_encode()-function to encode this object to JSON and echo it out.
This JSON-object will then be available in the success-method of the ajax()-method from jQuery. Then, you can access its members (e.g. the comment-count).

Using jQuery.post() to submit content and display what's going on

This is more of curiosity that anything, but I can think of several places (mainly in admin sections) where this could be useful. I know the title is confusing so this is what I mean:
Say you have a form that posts to example_cb.php. example_cb.php is a very large callback page that generates multiple thumbnails of an image, puts them in their respective directories, adds them to a database, etc. You already have the form posting by jquery with a function like this
$.post('example_cb.php', $(this).serialize(), function(data) {
// Success
}, 'json');
Before posting it updates a div to say "processing" of something. Then after it successfully completes the div fades out. However you want the div to show what is happening on the server side. i.e. Converting 200X200 thumb > Converting 350x350 thumb > Adding Records to Database > etc.
How can you accomplish this?
I know it's a loaded question, but I'm confident there are people on here smart enough to figure it out. If you need more info please comment :)
You could do something like -
Write each 'event' update to a database table
Write a page that retrieves the last n events from table
Use something like 'load' to call page update an onscreen div
with the updated progress.
Use 'setTimeout` to keep updating.
This could be accomplished most easily with using the push method, but I'm not too familiar with ajax push or comet technology, so I'll give you a pull solution.
Basically you need to create the initial ajax request to start the processing. Then, you need to have another request running in a tight loop that checks against a php page for the current status. For example, on the php page doing the processing, you can update a _SESSION key that stores the current processing information (like "Converting 200X200 thumb") at each step. Another php page will exist purely to print that information and you can retrieve it with the JS running in a loop.
pusher like services may be used for bi-directional communication.
I'm putting it down for reference, though this would be overkill for such a simple scenerio.

AJAX autorefresh making only last entry visible !

Iam new to PHP . I wanted to make a forum where users can ask questions.I am using ajax to auto refresh the page.But it creates some problems...
Firstly, if I make that particular div ,where most recent question will be displayed,refresh only the latest question is displayed .
let me clear it with an ex :
User A opens the forum
He gets questions qlatest,q1,q2,q3 . Where div containg qlatest refreshes every 1 sec
User B posts a question qlatest2
qlatest is replaced by qlatest2 !
Now should I make whole div conatining all the questions make refresh?
If I understand correctly you want to create something like the Twitter feed where the latest item is displayed on top of each other.
The reason that the entire DIV refreshes is because you are rewriting the entire inner HTML of that DIV. To avoid this, use .appendChild() and program your PHP callback file to only pull the latest record from the database.
http://www.ezineasp.net/post/Javascript-Append-Div-Contents.aspx
JQuery also has some very useful functions adding children. I suggest using a Javascript library if you are new to AJAX calls.
You have to:
Add some data source that returns last asked question.
Invoke that data source on a constant interval and load returned question into the div..
The simplest to explain is the following solution:
Write JavaScript code that uses JS builtin function setInterval() to load eg. script last_question.php into the div. You can do it eg. using jQuery load() function, which can look eg. like this (assuming your div has ID of "last_question"):
jQuery('#last_question').load('last_question.php');
Of course it can be optimized. To do so, read about:
Long polling
JSON format
jQuery.requestJSON() jQuery function
Maybe some effects to make the question change smoother (like slide out and slide in)

Categories