I have a class which gets a result from the database and the result is being looped through, and the database is being updated regularly but i dont want to keep refreshing the page because of some reasons.
//file class.php
class order {
function getOrders(){
//gets data from database
}
}
//file main.php
$ai = new order();
$orders = $ai->getOrders();
foreach($orders AS $order){
//data displayed in a table
}
I want the table to be automatically updated without page reload.
I know i have to use ajax but i have no idea what to implement that in oop
Use something like this.
$(function () {
setInterval(function () {
$("#liveTable").load("path/to/orderList");
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="liveTable"></div>
You need to use javascript and jQuery on your html page so as to reload a portion of the page.
you can add the following in your html page's head:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function()
{
theIntervalHandle = setInterval(fetchNewOrders,3000);
});
function fetchNewOrders()
{
$('#ordersDiv').load('http://your.web.address/class.php');
}
</script>
and that
<div id="ordersDiv"></div>
inside your html file's body where you want the dynamic content to appear.
this assumes that the file that creates the output is called class.php and fetches data each 3 seconds as per second is quite often and can cause problems should your traffic increase beyond a few tens of users...
Related
I'm loading content into a div with jquery's load() function and refresh that div every 15 seconds (it checks for a status).
For some reason after the first reload / refresh of the div, the session data is lost.
The exact code I'm using is very long, so a basic version of what I'm doing is this:
load.php
<?php
session_start();
$_SESSION['testvalue'] = "TESTVALUE";
?>
<div id="loaddiv"></div>
<script src="js/jquery.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
});
var $container = $("#loaddiv");
$container.load("load_test.php");
var refreshId = setInterval(function()
{
$container.load('load_test.php');
}, 10000);
});
})(jQuery);
</script>
load_test.php
<?php
session_start();
echo $_SESSION['testvalue'];
?>
Works fine when page loads initally and displays TESTVALUE, after the div refreshs there is no more output however.
Anyone experienced this before and knows what's going on ?
//EDIT
I'm one step further to solving this:
On the main page I'm selecting some things from my mysql db and putting this into the session, in the subpage (the one that jquery load() loads ) I am now just outputting the session values.
There's absolutely nothing on the subpage but this:
<?php
session_start();
echo $_SESSION['test_one'];
echo $_SESSION['test_two'];
?>
<?php echo session_id(); ?>
When jquery load() is triggered the second time, the values in
$_SESSION['test_one']; and $_SESSION['test_two']; change ... (It is running the mysql query again and putting something else into the session)
The values for the session get set on the mainpage, so why would refreshing the subpage run the mysql query on the main page again ?!
.net developer trying to do a php site for a friend, so far everything is going great but I was wondering if php has something like a textchanged event. Here is what I want to do, I want a drop down box to be appended with data retrieved from a database based on what the user enters in a textbox above(Using the text in the textbox as a parameter to retrieve data from a database and append it to the drop down without reloading the entire page.)
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//Do stuff
}
The block off code above is in asp.net but i want to implement something similar in php.
That is not how php works. however you can make a ajax call like this with jquery:
<?php
//array, object or db result you use to fill your dropdown
$array = array('pipo', 'kees', 'klaas', 'klaas1', 'jan', 'meneerje', 'poep', 'hessel', 'kaas', 'ietsandersd', 'smit', 'cowoy', 'nog zo iets');
//if we want to search we search and only return the new found options
if(isset($_REQUEST['keyword'])){
$new_array = array();
foreach($array as $value){
if(strpos($value, $_REQUEST['keyword']) !== false){
$new_array[] = $value;
}
}
}
else{
$new_array = $array;
}
$options = '';
foreach($new_array as $key => $option){
$options .= "<option value='$key'>$option</option>";
}
$selectbox = "<select name='selectbox' id='drop_down'>$options</select>";
if(isset($_REQUEST['keyword'])){
echo $options;
}
else{
// with the \ we escape the "
echo "<html>
<head>
<title>ajax selectbox</title>
<script src=\"http://code.jquery.com/jquery-latest.min.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
$(document).ready(function () {
$('body').on('keyup', '.search', function(){
var data = $('.search').serialize();
$.post('ajax_selectbox.php', data, function (data){
$('#drop_down').html(data);
});
});
});
</script>
</head>
<body>
<input type='text' name='keyword' class='search' />
$selectbox
</body>
</html>
";
}
?>
explanation:
java script,
first we include the online jquery library, you can also download the library and include it from your own web server.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
// first we wait unit the html page is loaded
$(document).ready(function () {
//then we wait for a keyup event in the element with class="search" we use the css sector . for classes like .search
$('body').on('keyup', '.search', function(){
//when we type inside the .search textbox we serialize the element like a form would do. this takes the name and the value and puts it in a array.
var data = $('.search').serialize();
// then we post with ajax back to our php file or an other php file. its you own decision. the data variable is the serialized data form .search
$.post('ajax_selectbox.php', data, function (data){
// at least we use a calback for when the ajax event has finnest and we use the jquery html function to put the new options inside the drobbox with id="drop_down". we use the css id selector # to select the select box.
$('#drop_down').html(data);
});
});
});
</script>
note that I use jquery (and a lot of large players on the web use jquery) and if you know a little java-script the syntax can be disturbing.
In jquery we have a large set of methots we can use directly like:
$.post();
if you want to use the returned data from that function we create a calback function like:
$.post( function(param_ returned_by_parent_function){
//do stuf
});
An other way of using jquery and this is actually the idea behind it is query to a html element and then do stuff with it like this.
$('html_element_query').do_something_with_this();
of course this is just a basic basically explanation but maybe you get the idea.
You can use javascript onChange handler and send the current value to php via AJAX
https://developer.mozilla.org/en/docs/DOM/element.onchange
http://www.w3schools.com/ajax/
PHP does not know what happens on the client. If you want some events on the client to trigger actions, you have to code that yourself (usually in JavaScript).
PHP itself has no awareness of events happening on the front end. You can, however, plug the functionality (kind of) by using a mixture of Ajax and PHP. Ajax will watch for the events and PHP will process data sent to it from that Ajax.
I suggest using jQuery and checking out http://api.jquery.com/Ajax_Events/
I made a very simple PHP Event Dispatcher for myself, it is testable and has been used on my websites. If you need it, you can take a look.
I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/
Right now I use a pagination system that requires url like
http://mypage.com/index.php?page=1
http://mypage.com/index.php?page=2
http://mypage.com/index.php?page=3
http://mypage.com/index.php?page=4
etc...
So it uses $_GET method to find out what page the user is on.
I decided to switch most of my website to ajax and came over a problem. When I use Ajax to load new content on a page the url stays the same all the time e.g. http://mypage.com/index.php . Therefore pagination system I use is useless.
I was not able to find efficient AJAX pagination systems, (e.g some where lagy, most required user to scrol to the tiop each time he / she clicked on a next page, because they stayed at the bottom of the page when they clicked next page. etc...)
So I decided to ask you lot if anyone has an efficient pagination solution that works with ajax.
Example of what needs to be paginated:
$sql = mysql_query("SELECT * FROM myMembers WHERE username='$username' LIMIT 1") or die (mysql_error("There was an error in connection"));
//Gather profile information
while($row = mysql_fetch_assoc($sql)){
$username = $row["username"];
$id = $row["id"];
$data_display .= '<b>'.Name.'</b> has an id of <span style="color: f0f0f0;">'.$id.'</span>';
}
<!doctype>
<html>
<?php echo "$data_display"; ?> //and I need to paginate this entries
</html>
jQuery that loads new content from different pages into #content div
<script type="text/javascript">
function viewHome(){
$('#woodheader').load("inc/home_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/home.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewAbout(){
$('#woodheader').load("inc/about_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/about.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewProducts(){
$('#woodheader').load("inc/products_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/products.php", function () {
$(this).hide().fadeIn(700)
});
}
</script>
Pagination is not as hard as you can think, you can use jQuery's load() function to load content into an element with the page's content.
So for example you have:
<div id="page-content"></div>
Page 1
Page 1
Page 3
<script>
$.ready(function(){
var currPage = <?=$pageNumber; ?>; // The page number loaded on page refresh
$('#link1,#link2,#link3').onclick(function(){
// Get the first number inside the id
var pageNum = parseInt($(this).attr('id'));
// Don't load the same page
if(currPage == pageNum) return;
// Show loading animation or whatever
// Load the page using ajax
$('#page-content').load('pages.php?page='+pageNum, function(){
// End loading animation
currPage = pageNum;
});
return false; // Important for not scrolling up
});
});
</script>
Regarding the url, you have three options to choose from when a user clicks a page link:
Just load the page with no changing of the url
Use the HTML5 history.pushState(see MDN resource) if supported and with option 3 as fallback for unsupported browsers
Use #page1, #page1 etc. as the href value of the links so that the user knows on what page they are on and parse the value of the url in php:
$uri = explode('#page', $_SERVER['REQUEST_URI']);
$pageNumber = intval($uri[1]);
I would create a index.php that doesn't load any $data_display initially.
Internally in javascript I would keep a variable named $page that would initially equals 1.
After load it would make a ajax call to names.php?page=$page and pass the results to a handler that presents it to the user.
Then on the links to "back" and "next" I would put a javascript function that first sets $page to the previous or next number, then calls names.php?page=$page and pass the results to the same handler.
I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}