I have a PHP page which queries some data from a PostgreSQL database. The data must be always shown up to date, and thus I must refresh it every single second. Right now I'm using but it refresh the entire page, which is not what I want to.
What matters to me is actually in here
I already looked it up and even saw some posts in here, but nothing suited me very well yet. For now (as matter of learning, I'd say) I don't want to get all the PHP query statements, put in another PHP file and refresh it.
I do want a solution for refreshing partially a PHP part of a page.
The best way to do this is using AJAX.
(Sending requests in the background via JavaScript,
and loading the results into the webpage)
There are a lot of TuTs out there.
If you use JQuery, and create a Php Script which when called will print out the data as you like.
Using the $.ajax feature of JQuery will enable to you dynamically load that page, then you can insert it into the page using $('#MyID').html('New Content');.
An example of this, using a script called "refresh.php" with the a dynamic variable of 'ID', would be
$.post('refresh.php', { ID: 1 }, function(result){
$('#MyID').html(result);
}
You could also use json_encode() to separate the output data, via using the JQuery function $.parseJSON
An example of this would be
$.post('refresh.php', { ID: 1 }, function(result){
var data = $.parseJSON(result);
$('#MyID').html(data.ID);
}
That would access the JSON encoded variable of "ID", returned from PHP.
Related
Alright, so I have a PHP app that, in essence, fills up an array with references to elements in an XML file, does a shuffle() on the array to randomise it, then cycles through the array, displaying the data from the array (and ergo the XML file) on the screen.
My current code works fine - It fills the array, shuffles it, and displays the 0th index (which -is- random). My problem lies in the fact that I want to be able to reload the content on the page dynamically, without losing the data in the arrays, but not link to a different page. More specifically, I want to be able to cycle through the array on the click of a button (without totally reloading the page, losing the valuable data in the array).
I tried using some hidden form fields to load the values of the array into a temporary array, then feed them back in as the page reloads, but to no avail. I find a lot of bugs this way, and it's quite clearly a quick-n-dirty way of doing it.
Essentially, I want the code to do something like this:
$heaps_array = array(...); // Populated by, let's say 3 strings, for argument's sake
shuffle($heaps_array);
echo $heaps_array[0];
// User clicks the Next button...
// Get rid of the $heaps_array[0] from the page content, and...
echo $heaps_array[1];
// User clicks the Next button...
// Get rid of the $heaps_array[1] from the page content, and...
echo $heaps_array[2];
// User clicks the Next button...
...
PHP has a / is request based interpreter language so you need to run a script every time you need something from server. You can't have those arrays always in memory without using some storage engine (memcached, MySQL, you name it).
As others have said, you can send the array to the frontend and manipulate it in JavaScript. That way you won't load the server and have all data in memory.
Cant you send the array to the client side (the dirty way, not ajax) ?
Then display values with js.
i mean:
echo 'var array = new Array('.implode(',', $array).');';
Otherwise you will need more sofisticated method, the best is to build a mini webservice and get values through an AJAX query.
You have a few options here, but you need to understand that PHP is a server side language that runs and finishes before the browser even sees the page content. To do dynamic content, thats where javascript and ajax come into play. I recommend a javascript framework such as jQuery that makes AJAX calls simple.
Some ways to do it:
1) Output the entire php array into a javascript variable on page. Do all of the array sorting using javascript. No AJAX.
2) Use php to sort the array, store it in a session variable. Use AJAX to request new data from the array in session memory, resort the array if necessary and return the value you need.
3) Use an AJAX call to request and return the entire sorted PHP array. Use javascript to do with it as you wish.
Depending on the size of the data you wish to return, you may want to minimise amount of data request through AJAX and the client side processing, and just use PHP to do all of the array stuff then return the exact values you need.
Just throwing PHP's session management out there since no one has. http://php.net/session_start
Just a quick question. If I use a Pagination for my website and am expecting a lot of results, is it better to use jQuery or just a basic PHP/MySQL one that just loads a new page?
If I use jQuery and I have over 300 results from the database, will it have to load it all at once on the initial page load? That might take a long time to load. Or can you make it load only the first 10, and then when you go to Page 2 it will load the next 10?
Just wondering if you have any suggestions for my situation, and if you recommend any good scripts I can use for it.
Thanks!
IMO, start with "basic" PHP/MySQL pagination (load a new page each time the user changes pages).
Once you've got that working, if you want it, then add in jQuery pagination on top. All the jQuery pagination would do is load the new page of results via AJAX, rather than loading an entire new page.
So, the key here is how you handle paginating results via javascript (jQuery). If you render all 300 results on the page and simply hide results 200-300 (and reveal them via javascript), your page will still be really slow to render initially, and you'll be taxing the database with a query that could be optimized via a limit (pagination).
On the other hand, if you asynchronously query for more results via say, an asynchronous GET request to a web-service that spits the data out via JSON, you can both have a responsive page and avoid a taxing, limitless query.
Using PHP / MySQL and post-backs to handle the issue also prevents the long-initial page load + taxing query.
So, in summary, I'd absolutely paginate your results. I would also suggest you do the following:
1) First architect things using purely PHP / MySQL. So, for instance:
/results/?start=0&limit=20 (Show results 0-19)
/results/?start=20&limit=40 (Show results 20-40)
2) Then if you want to provide a responsive, javascript mechanism for loading more, extend your page so that it can spit out JSON with a format parameter:
/results/?start=0&limit=20&format=JSON
So if format=JSON instead of rendering the HTML, it'll just spit out the JSON data, paginated.
3) Then wire up the javascript to use the JSON data to dynamically load in more content:
$.get('/results/?start=' + start + '&format=JSON', function(data) {
// Process and display data
});
Hopefully that makes sense!
You've tagged your question with ajax, that's the answer... You should use a combo of PHP/MySQL + Ajax to make the things faster and smoother.
Here is a very popular plugin which implement the client interface: JQGrid
I'm looking for a library which do this :
Retrieve a JSON through an AJAX call
Populate table with the JSON
Update in real time the table with the JSON (call every x seconds) and only delete or hide the rows wich are deleted or insert the new rows.
/Editing after first answer
Ok I guess my first explanation was not good.
Retrieving through jQuery a JSON and build a table is good, I could do that, but my request was more on the other part.
I'm looking for a library to display the result in a special way.
Let me explain.
Json request 1 send :
1;Tomato 2;Apple 3;Salad 4;Carot
Json request 2 send :
1;Tomato 3;Salad 4;Carot 5;Potatoes
I would like the second row disapear with a effect (fadeOut) and the rows below move Up. For the row 5, i just want a new row appears with a fade in.
Is that more clear?
Is there any library existing doing this?
I'm doing it in PHP, but i hope to write all this in JS.
The user could just look the table and see the new rows appearing and the old rows deleting.
Any ideas or am I supposed to write it from scratch?
You can get the json like this (use get or post, ill show post here):
function do_json_live(){
$.post('url.php','somedata', function(returnJSON){
alert(returnJSON);
//do something with the `returnJSON`
setTimeout(do_json_live, 2000); //2000 ms = 2 seconds
},'json');
}
If you want something friendly and full of various useful features, you can use jQuery plugin called DataTables.
It provides API allowing you to provide new data from the server on request: http://www.datatables.net/api
It works for simple implementations also, is pretty customizable, allows to change its outlook etc.
Hope this is useful.
Here is a really good article on different polling/comet techniques that you will want to look into. It breifly describes each and points out some pitfalls you might not think of.: http://query7.com/avoiding-long-polling. Also here is a jquery plugin for long polling: http://enfranchisedmind.com/blog/posts/jquery-periodicalupdater-ajax-polling/
Try Jquery Grid Plugin. You can retrieve JSON from server and build a grid on the client side. Take a look at the web site, there are some examples including php.
First I would read this, but the code is actually really simple.
On your front end, you'd have your table
<table id="myTable"></table>
Then you'd make your AJAX post within JQuery
$.ajax({
url: "yourphpfile",
data: <data you want your php file to read>
success: function(data){
$('#myTable').html(data);
}
});
Your method in php would take in your posted data, it would create an HTML string of a table element, and then you'd set your table's innerHTML on the front end with .html() built into JQuery -- that way you never have to worry about showing/hiding, everytime you post, your given the table itself, so you just display exactly that, you can handle all the fancy stuff server side.
You could use the awesome jqGrid plugin.
To do the autorefresh, you should do this:
setInterval(function(){
$("#grid1").trigger("reloadGrid");
}, 10000);
Hope this helps. Cheers.
If real-time updating is truly required, as Neal suggested, Comet or Stream-Hub would be one avenue worth checking into.
As for the interface, I recently have been using JQuery Templates, and when reconciling added / removed / updated records, I use JQuery selectors to clear & update, and use Templates to add in new records. And because I'm using JQuery in all 3 events, I could easily integrate their motion / visual effects.
JQuery Templates
JQuery Selectors
JQuery Effects
Stream-Hub
I myself only needed polling (every 15 seconds) so I'm using Robert Fischer's improved JQuery PeriodicalUpdater
JQuery Periodical Updater
I am using some PHP script to add some data from a complex form to MySQL db and then showing it all in some HTML table. Everything works just fine, but I would like to 'upgrade' my script with jQuery and (I suppose) AJAX.
What I would like to do is when user submits data, the row (or <div>) shows up in the HTML table without refreshing a page. Form and table are on same page, of course...
Some guidelines would be really helpful because I'm not sure should I even use AJAX or something else for my needs. Links for some tutorials will be also great :)
Thanks a lot for any help!
An easy way to do this is using jQuery POST method
http://api.jquery.com/jQuery.post/
When the user submits the data, you use jQuery to post the data to a PHP handler, which saves the data to the database and returns a HTML formatted row to add to your table.
Here's a good example:
http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/comment-page-1/
I had used this tutorial to implement a comment system on one of my projects. It uses ajax and works really well. I believe that this is what you need.
You'll need:
A php page where to submit the form. Ideally this page will return the result as a JSON object (PHP has some handy JSON functions to convert PHP arrays and objects directly to a proper JSON string). Don't forget to include some error information in the JSON object you return. This can have the form:
{
"errorCode": 0,
"result":
{
"var1": value1,
"var2": value2
}
}
Some javascript to submit the form. This can be done nicely with jQuery.ajax, jQuery.post or jQuery.get functions.
Some javascript to handle the result from the PHP script. This will be a callback function that you give to the jQuery.ajax, jQuery.post or jQuery.get functions. This script will either:
display the errors to the user (you can set some text in a div for example using jQuery("#error").html("My error message");)
Insert the row in your table. You can build HTML elements dynamically using jQuery.append and jQuery.html functions.
I have a HTML page. Clicking on one link within the page runs a php function which adds a HTML table to the page (implemented with AJAX, php function is in a separate php file).
Now, I have a button on the page which is supposed to run another php function which should pick up the data from the table and do something with it. I don't know how to get the data from the table because:
I don't know how to reference (get) a HTML element through php.
My php function is in a separate file.
What if I put everything from the table in POST or GET arguments? Is there a way to reference the table and iterate its rows and get the data that way? Thanks.
This is not a job for PHP, you should use Javascript to capture the table contents and then manipulate them whatever way you would like. If on the other hand the table contents never change then you can just put them into your PHP function.
You can pull the values of the table by first setting an ID for the table like so:
<table id="someTable">
<tr id="someRow">
<td>Data</td>
<td>Data2</td>
</tr>
</table>
Then you can call the values from the table using JavaScript:
var row = document.getElementById("someRow");
var cellValues = row.getElementsByTagName("td");
This will put all of the cells into an array. Then you can put them into variables.
var firstCell = cellValues[0].innerText;
var secondCell = cellValues[1].innerText;
Then you can put it into an AJAX Request and send it to your PHP function to be processed.
This will send a GET or POST request to yourfile.php and then you can manipulate the cell rows in whatever manner you would like and send back a result by echoing it out in the PHP file. You can retrieve the results by making the callback function.
Hope this helps,
Chris
I don't know how to reference (get) a HTML element through php.
Use JavaScript to get the data from the table.
My php function is in a separate file.
Create another AJAX request to get it processed by PHP,
You cannot reference an HTML Table from PHP. Your JS should just send the table data, extracted out of the html table, as JSON. Your PHP can respond with some more JSON that your JS can use to manipulate the existing table.
A php file that is used as the response to an XHR should not generate JS. Just JSON.
Yes you have to put the data in POST arguments. Do not use GET since the table might get to big. You can use javascript to get all the data from the elements. Send the data with ajax to a php page. Now you can get the post data and so somehting with it (For example persisting).
The reason that you can't get it directly with php is because html and javascript are run by the browser (client side) while php runs in the web server (Server side). You need some sort of communications between these machines to use each others resources.