include php script in html webpage - php

I have a 165 line php script that I would like to integrate into my html webpage.
The php script parses csv files uploaded by the user for column names. The html page allows the user to select variables from a dropdown menu. I want to let the php script run when a user uploads a file so the dropdown menu can be populated with the results from the php script.
this the html
<!DOCTYPE html>
<html lang="en">
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style type="text/css">
body {
padding-left: 11em;
}
ul.navbar {
position: absolute;
top: 2em;
left: 1em;
width: 9em }
h1 {
font-family: Helvetica, Geneva, Arial,
SunSans-Regular, sans-serif }
.float-child {
width: 50%;
float: left;
padding: 20px;
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
</style>
<body>
<!-- Page content -->
<div class="w3-content" style="max-width:2000px;margin-top:46px">
<div class="w3-container w3-content w3-padding-64" style="max-width:800px" id="contact">
<h2 class="w3-wide w3-center">Create Crosstabs</h2>
<ul class="navbar">
<li>Upload Crosstab Data
<li>Create Crosstab
<li>View Crosstab
<li>View Past Crosstabs
</ul>
</div>
<div class="float-container">
<div class="float-child">
<div class="green">Choose Crosstab
<label for="cars">Variable for Column 1: </label>
<select name="cols" id="cols">
<option value="Age">Age</option>
<option value="Ethnicity">Ethnicity</option>
<option value="Income">Income</option>
</select>
<br>
<label for="cars">Variable for Column 2: </label>
<select name="cols" id="cols">
<option value="Age">Age</option>
<option value="Ethnicity">Ethnicity</option>
<option value="Income">Income</option>
</select>
<br>
<button id="1" onClick="reply_click(this.id)">Create</button>
</div>
</div>
<div class="float-child">
<div class="blue">Sucessfully Uploaded Records
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
</div>
</div>
<h1><?php echo "This message is from server side." ?></h1>
<!-- End Page Content -->
</div>
<!-- Image of location/map -->
<img src="/w3images/map.jpg" class="w3-image w3-greyscale-min" style="width:100%">
<script>
// Automatic Slideshow - change image every 4 seconds
var myIndex = 0;
carousel();
function reply_click(clicked_id)
{
alert(clicked_id);
}
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 4000);
}
// Used to toggle the menu on small screens when clicking on the menu button
function myFunction() {
var x = document.getElementById("navDemo");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
} else {
x.className = x.className.replace(" w3-show", "");
}
}
// When the user clicks anywhere outside of the modal, close it
var modal = document.getElementById('ticketModal');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
</script>
</body>
</html>
and this is the php
<?php
//Connection
$db = pg_connect( "host=localhost dbname=dbname user=postgres password=password" );
if(!$db) {
echo "Error : Unable to open database";
} else {
echo "Opened database successfully";
echo "<br>";
}
//Using this to test queries
function testQuery($ret, $completedmsg=""){
if(!$ret){
echo pg_last_error();
echo "<br>";
}else{
echo $completedmsg;
echo "<br>";
}
}
//Added a break function, I was sick of adding breaks for echoing
function break_html(){
echo "<br>";
}
//Getting file
$CSV_File = "pi2sample5.csv";
$csv = file($CSV_File);
//Get type of each column (count(int), percentage(float), ""(varchar))
$type = explode(",", $csv[0]);
//Get each column name
$column_name = explode(",", $csv[1]);
//Remove .csv (lazy, but I will add a regex here)
$table_name = substr($CSV_File,0,-4);
$table_name = preg_replace('/\..*/', '', $CSV_File);
//Check if table exists
$checkExists = "SELECT EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename =" . "'" . $table_name . "'". ")";
$exists = False;
$ret = pg_query($db, $checkExists);
$i = 0;
while ($row = pg_fetch_row($ret))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
if($c_row == 't'){
$exists = True;
}
next($row);
$y = $y + 1;
}
}
//If table exists, skip creation
if(!$exists){
//Create new Table
$sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "()";
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error();
echo "<br>";
}else{
echo "CREATED NEW TABLE";
echo "<br>";
}
//Making columns with correct variable types and names
$i = 0;
while ($i < count($column_name)){
if ($type[$i] == "Count"){
$new_type = "INT";
}elseif ($type[$i] == "Dollars"){
$new_type = "INT";
}elseif ($type[$i] == "Percentage"){
$new_type = "float8";
}else{
$new_type = "VARCHAR(12)";
}
$new_column = preg_replace('/[^A-Za-z0-9]/', '', $column_name[$i]);
$i = $i+1;
$ret = pg_query($db, "ALTER TABLE " . $table_name . " ADD COLUMN " .$new_column. " " . $new_type);
if(!$ret){
echo pg_last_error();
echo "<br>";
}else{
echo "ADDED NEW COLUMN: " . $new_column;
echo "<br>";
}
}
//Copy file into a safe "previous" version
if (!copy($CSV_File, "old" . $CSV_File)) {
echo "failed to copy $file...\n";
}
//Remove first row of CSV (count, count, percentage, etc...)
$new_csv = array_splice($csv, 1);
file_put_contents($CSV_File, implode("", $new_csv));
$createCSVtable ="COPY " . $table_name . " FROM '/home/monty/PI2/PI2Team/" . $CSV_File . "' DELIMITER ',' CSV HEADER;";
file_put_contents("rewritten.csv", $old_csv);
$ret = pg_query($db, $createCSVtable);
testQuery($ret);
//Restore the file with removed row
if (!copy("old" . $CSV_File, $CSV_File)) {
echo "failed to copy $file...\n";
}
if(!unlink("old" . $CSV_File)){
echo "Couldn't delete old$CSV_File";
}
}
//GET VARIABLES/COLUMN NAMES
$ret = pg_query($db, "SELECT
column_name
FROM
information_schema.columns
WHERE table_name =" . "'" . $table_name . "'" );
if(!$ret){
echo pg_last_error($db);
} else{
echo "SHOWING TABLE";
//echo pg_fetch_row($ret);
}
echo '<html><body><select name="variables">';
//Putting variables (column names) into dropdown menu in html
$i = 1;
while ($row = pg_fetch_row($ret))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
echo "<option value=" . "'" . $c_row . "'" . ">" . $c_row . "</option>";
next($row);
$y = $y + 1;
}
$i = $i + 1;
}
echo "</select>";
pg_free_result($ret);
pg_close($db);
?>

Just set up your web server so that HTML files parse through PHP. This varies depending on your server. Alternatively, just save the file as .php and it should run!

Related

How to fix an array of inputs and display it correctly

This Question is a bit long and I have edited too much to reduce my code but I hope anyone can help me out please!
I'm working on a Math test in times table project with php which will ask the user to enter his name and then ask him 10 questions like "2 x 2 = ?" giving four buttons to choose an answer and then after answering 10 questions the user will be redirected to result.php page which will show the result and here is what I wrote so far in homePage.php:
<?php
session_start();
if (isset($_POST['submit']) ) {
$_SESSION['QuestionNumber'] = 1;
$_SESSION['CorrectAnswers'] = 0;
$_SESSION['QuestionsAsnwered'] = 0;
$_SESSION['QuestionsAnswered'] = 0;
header("location: MathTest.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<h1 align="center">Math Test</h1>
<form method="POST" action="">
<div style="text-align: center;">
<input type="submit" name="submit" value="Begin Test"">
</div>
</form>
</body>
</html>
and in MathTest.php which contains the problem:
<?php
session_start();
//just controlling user answer no problem here
if (isset($_POST[$_SESSION['UserAnswer']])) {
if ($_SESSION['QuestionNumber'] == 10) {
header("location: result.php");
}
if ($_SESSION['UserAnswer'] == $_SESSION['CorrectAnswer']) {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['CorrectAnswers'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
} else {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
}
}
//I think that my problem(written down) is here
function QuestionGenerator(){
$rnd1 = rand(1, 12);
$rnd2 = rand(2, 12);
$CorrectAnswer = $rnd1 * $rnd2;
$WrongAnswer1 = $CorrectAnswer - 2;
$WrongAnswer2 = $CorrectAnswer + 2;
$WrongAnswer3 = $CorrectAnswer + 4;
$_SESSION['rnd1'] = $rnd1;
$_SESSION['rnd2'] = $rnd2;
$_SESSION['CorrectAnswer'] = $CorrectAnswer;
$_SESSION['WrongAnswer1'] = $WrongAnswer1;
$_SESSION['WrongAnswer2'] = $WrongAnswer2;
$_SESSION['WrongAnswer3'] = $WrongAnswer3;
$_SESSION['AnswersArray'] = array($_SESSION['CorrectAnswer'], $_SESSION['WrongAnswer1'], $_SESSION['WrongAnswer2'], $_SESSION['WrongAnswer3']);
}
function EchoAnswers($array) {
shuffle($array);
echo "<form method='POST' action='' ";
foreach ($array as $_SESSION['UserAnswer']) {
echo "<button><input style='width: 200px; height: 100px; font-size: 75px;' type='submit' name='" . $_SESSION['UserAnswer'] . "' value='" . $_SESSION['UserAnswer'] . "' ></button";
}
echo "</form>";
}
?>
<!DOCTYPE html>
<html>
<body>
<?php echo "<h1 align='center' style='font-size: 75px;'>Question " . $_SESSION['QuestionNumber'] . " of 10</h1>"; ?>
<h2 align="center" style="font-size: 60px"><?php echo $_SESSION['rnd1'] . " X " . $_SESSION['rnd2'] . " = ?" ?></h2>
<div align="center">
<?php EchoAnswers($_SESSION['AnswersArray']) ?>
</div>
</body>
</html>
the problem is when I click on any button it will only shuffle the answers but if I press the last button it will work full functionally
The problem I had was that there is 4 submit buttons each with different name tag so the session will only store the last input button and will make it functional but for the others it will only refresh the page with no different because they are not being controlled by php code so to solve this problem I only changed the EchoAnswers function like this:
function EchoAnswers($array) {
shuffle($array);
echo "<form method='POST' action='' ";
foreach ($array as $_SESSION['UserAnswer']) {
echo "<button><input style='margin: 10px; border: 3px solid black; background-color: lightblue; width: 200px; height: 100px; font-size: 75px;' type='submit' name='UserAnswer' value='" . $_SESSION['UserAnswer'] . "' ></button";
}
echo "</form>";
}
the name tag was also set to $_SESSION['UserAnswer'] so I changed this part to a normal name and I also changed the php code like this:
if (isset($_POST['UserAnswer'])) {
if ($_SESSION['QuestionNumber'] == 10) {
header("location: result.php");
}
if ($_SESSION['UserAnswer'] == $_SESSION['CorrectAnswer']) {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['CorrectAnswers'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
} else {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
}
}
the part that I have changed in php code is isset($_POST['UserAnswer']) because UserAnswer was set to $_SESSION['UserAnswer'] instead of normal name in the name tag.

Adding a counter to the table

I'm trying to add a counter to the table in the following code. but I couldn't be successful. Can I get a little help, please? thanks. Something like this:
$counter = 0;
$counter++;
if($counter % 33 == 0)
So that when the counter is added, table will continue after %33 on the right of the page, and it will continue like that, instead of going down the page.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="etc/sumain.css" />
</head>
<body>
<table class="tbresult">
<?php
include ("confige.php");
$query = 'select * from employees';
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect FROM employees"; // add column alias
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
echo "</table>";
}
}
mysqli_close($link);
?>
</body>
</html>
First, don't have an HTML form inside a table, this is not valid, AFIK, and can cause you many troubles in different browsers.
You need simply open the table once, then create a counter = 0 and on each while loop add 1 to it. Then check, if it divides by 33 than you close the table and open a new one. After the loop you close the last table.
The side by side alignment can be done with CSS, something like .tbresult {float: left; width: 200px;}
Something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="etc/sumain.css" />
</head>
<body>
<?php
include ("confige.php");
$query = 'select * from employees';
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect FROM employees"; // add column alias
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
// output data of each row
$table_row_counter = 0;
echo '<table class="tbresult">';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 33 == 0) {
echo '</table>';
echo '<table class="tbresult">';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
mysqli_close($link);
?>
</body>
</html>

How to get MySQL query to carry over with PHP Pagination?

I am trying to keep my pagination based on the query I am using, but my problem is, it only works on the first page of pagination, and after that the query reverts to the standard one without filters (page one shows my filter, but page two show all results). I am wondering if there is an effective method that will carry over my filtered query when I click my pages, I am just at a loss right now as to how to accomplish this. Here is my code currently:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style type="text/css">
#win-range, #gaa-range, #sv-range{
width: 160px;
font-size: 10px;
margin: 0 auto;
}
#win-range a, #gaa-range a, #sv-range a{
margin-top: 0px !important;
padding: 0 !important;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function(){
$("#win-range").slider({
range: true,
min: 1,
max: 1000,
values: [1, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minwins").val(ui.values[0]);
$("#maxwins").val(ui.values[1]);
$("#winamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#winamount").val($("#win-range").slider("values", 0) + " - " + $("#win-range").slider("values", 1));
});
$(function(){
$("#gaa-range").slider({
range: true,
min: 0,
max: 10,
values: [0, 10],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#mingaa").val(ui.values[0]);
$("#maxgaa").val(ui.values[1]);
$("#gaaamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#gaaamount").val($("#gaa-range").slider("values", 0) + " - " + $("#gaa-range").slider("values", 1));
});
$(function(){
$("#sv-range").slider({
range: true,
min: 750,
max: 1000,
values: [750, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minsv").val(ui.values[0]);
$("#maxsv").val(ui.values[1]);
$("#svamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#svamount").val($("#sv-range").slider("values", 0) + " - " + $("#sv-range").slider("values", 1));
});
</script>
<?php
include("includes/header.php");
include("includes/mysqli_connect.php");
$minwins = $_POST['minwins'];
$maxwins = $_POST['maxwins'];
$mingaa = $_POST['mingaa'];
$maxgaa = $_POST['maxgaa'];
$minsv = $_POST['minsv'];
$maxsv = $_POST['maxsv'];
$querySelection = $_POST['q'];
// FILTERING YOUR DB
$sortstats = $_GET['sortstats'];
$sortstatslow = $_GET['sortstatslow'];
// pagination
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
$postnum = mysqli_result($getcount,0);// this needs a fix for MySQLi upgrade; see custom function below
$limit = 6; //how many blog posts per page you will see.
if($postnum > $limit){
$tagend = round($postnum % $limit,0);
$splits = round(($postnum - $tagend)/$limit,0);
if($tagend == 0){
$num_pages = $splits;
}else{
$num_pages = $splits + 1;
}
if(isset($_GET['pg'])){
$pg = $_GET['pg'];
}else{
$pg = 1;
}
$startpos = ($pg*$limit)-$limit;
$limstring = "LIMIT $startpos,$limit";
}else{
$limstring = "LIMIT 0,$limit";
}
// MySQLi upgrade: we need this for mysql_result() equivalent
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
<div class="listingcontainer">
<div class="sidebar">
<h3>Sort By:</h3>
Most Wins
Best Goals Against
Best Save %
<hr/>
<h3>Custom Filter</h3>
<br/>
<div class="custom-filter">
<form name="filters" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="filters">
<label for="winamount">Win Range:</label>
<input type="text" id="winamount" />
<div style="clear:both;"></div>
<input type="hidden" id="minwins" name="minwins" value="0" />
<input type="hidden" id="maxwins" name="maxwins" value="1000" />
<div id="win-range"></div>
<br/>
<label for="gaaamount">GAA:</label>
<input type="text" id="gaaamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="mingaa" name="mingaa" value="0" />
<input type="hidden" id="maxgaa" name="maxgaa" value="10" />
<div id="gaa-range"></div>
<br/>
<label for="svamount">SV %:</label>
<input type="text" id="svamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="minsv" name="minsv" value="750" />
<input type="hidden" id="maxsv" name="maxsv" value="1000" />
<div id="sv-range"></div>
<input type="submit" name="submit" id="submit"/>
</form>
</div>
</div>
<div class="main-listings">
<h1>Current NHL Goaltenders</h1>
<?php
$result = mysqli_query($con, "SELECT * FROM Player ORDER BY PlayerID ASC $limstring");
if(isset($sortstats)) {
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ") or die (mysql_error());
}
if(isset($sortstatslow)) {
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ") or die (mysql_error());
}
if(isset($_POST['submit']))
{
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'
ORDER BY PlayerID ASC $limstring") or die (mysql_error());
}
while($row = mysqli_fetch_array($result)){
$name = $row['LastName'] . ", " . $row['FirstName'];
$wins = $row['Wins'];
$pid = $row['PlayerID'];
$image = $row['Picture'];
$gaa = $row['GAA'];
$sv = $row['SavePerc'];
echo "<div class=\"player-listing\">";
echo "<div class=\"image-holder\">";
echo "<span class=\"helper\"></span>";
echo "<img src=\"admin/thumbs/$image\" alt=\"$name\">";
echo "</div>";
echo "<div style=\"clear:both;\"></div>";
echo "$name";
echo "<table align=\"center\">";
echo "<tr>";
echo "<td style=\"border-bottom: 1px solid #212121;\">Wins</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">GAA</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">SV%</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$wins</td>";
echo "<td>$gaa</td>";
echo "<td>.$sv</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
// paging links:
echo "<div class=\"paging\">";
if($postnum > $limit){
echo "<span class=\"page-numbers\"><strong>Pages:</strong> </span>";
$n = $pg + 1;
$p = $pg - 1;
$thisroot = $_SERVER['PHP_SELF'];
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
echo " ";
}
// end paging
echo "</div>";
?>
</div>
<div style="clear:both;"></div>
Save you search filters in session and always check the session value is set for any search or not and pass that data into you query.until and unless nobody reset that search criteria and when your user reset that search criteria to null then put the value blank in the session for that session search variable.
You need to pass all filter conditions to the paginating link, for example
$filter = "minwins={$minwins}&maxwins={$maxwins}&mingaa={$mingaa}&minsv={$minsv}&maxsv={$maxsv}&q={$querySelection}";
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
In the code for getting filter conditions from $_POST you are using, change it to $_REQUEST because it should get from URL ($_GET).
Ex
$minwins = $_REQUEST['minwins'];
You could always use the below to create a list of URL keys (filters).
foreach($_GET as $key => $value){
$url_keys .= $key . "=" . $value . "&";
}
And then add that into your URL for next/prev page.
echo "next >>";
You will then be passing your filters through the URL and have access to them on the next page.

Unable to filter data from mysql

I tried to read data of my MySQL database, I created the fullcalendar and show up the event on calendar. However, it is unable to retrieve the data from my MySQL database.
The First php code :
<?php require_once('conn.php'); ?>
<?php $maxRows_RsCourse = 1000000;
$pageNum_RsCourse = 0;
if (isset($_GET['pageNum_RsCourse'])) {
$pageNum_RsCourse = $_GET['pageNum_RsCourse'];
}
$startRow_RsCourse = $pageNum_RsCourse * $maxRows_RsCourse;
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY tcid ASC";
$query_limit_RsCourse = sprintf("%s LIMIT %d, %d", $query_RsCourse, $startRow_RsCourse, $maxRows_RsCourse);
$RsCourse = mysql_query($query_limit_RsCourse, $conn) or die(mysql_error());
$row_RsCourse = mysql_fetch_assoc($RsCourse);
if (isset($_GET['totalRows_RsCourse'])) {
$totalRows_RsCourse = $_GET['totalRows_RsCourse'];
} else {
$all_RsCourse = mysql_query($query_RsCourse);
$totalRows_RsCourse = mysql_num_rows($all_RsCourse);
}
$totalPages_RsCourse = ceil($totalRows_RsCourse/$maxRows_RsCourse)-1;
?>
<?php
$tbl_name="tbl_course"; // Table name
$totalcount = 0;
// Connect to server and select database.
mysql_connect("$hostname_conn", "$username_conn", "$password_conn")or die("cannot connect server ");
mysql_select_db("$database_conn")or die("unable to connect");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
// echo "<table><tr>";
// echo "<td>" . $rows['id'] . "</td><td>" . $rows['title'] . "</td><td>" . $rows['start'] . "</td><td>" . $rows['end'] . "</td><td>" . $rows['url'] . "</td><td>" . $rows['allDay'];
// echo "</td></tr></table>";
$event[$totalcount]['tcid']=$rows['tcid'];
$event[$totalcount]['courseid']=$rows['courseid'];
$event[$totalcount]['coursename']=$rows['coursename'];
$event[$totalcount]['startdate']=$rows['startdate'];
$event[$totalcount]['starttime']=$rows['starttime'];
$event[$totalcount]['enddate']=$rows['enddate'];
$event[$totalcount]['endtime']=$rows['endtime'];
$event[$totalcount]['allday']=$rows['allday'];
$totalcount++;
}
for ($i=0; $i < $totalcount; $i++)
{
$tmp1 = explode("-",$event[$i]['startdate']);
$tmp2 = explode(":",$event[$i]['starttime']);
// 0 = hour, 1 = minutes, 2 = seconds,
$x = 0;
foreach ($tmp1 as $date_values_1)
{
$event_start_date[$i][$x] = $date_values_1;
$x++;
}
$y = 0;
foreach ($tmp2 as $time_values_1)
{
$event_start_time[$i][$y] = $time_values_1;
$y++;
}
$tmp3 = explode("-",$event[$i]['enddate']);
$tmp4 = explode(":",$event[$i]['endtime']);
$a = 0;
foreach ($tmp3 as $date_values_2)
{
$event_end_date[$i][$a] = $date_values_2;
$a++;
}
$b = 0;
foreach ($tmp4 as $time_values_2)
{
$event_end_time[$i][$b] = $time_values_2;
$b++;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0046)http://localhost/calendar/demos/db_display.php -->
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type>
<link href='css/fullcalendar.css' rel='stylesheet' />
<script src='js/jquery-1.9.1.min.js'></script>
<script src='js/jquery-ui-1.10.2.custom.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<SCRIPT>
$(document).ready(function() {
var start_year = new Array(<?php $totalcount?>);
var start_month = new Array(<?php $totalcount?>);
var start_day = new Array(<?php $totalcount?>);
var end_year =new Array(<?php $totalcount?>);
var end_month =new Array(<?php $totalcount?>);
var end_day =new Array(<?php $totalcount?>);
var start_hour =new Array(<?php $totalcount?>);
var start_mins =new Array(<?php $totalcount?>);
var end_hour =new Array(<?php $totalcount?>);
var end_mins =new Array(<?php $totalcount?>);
<?php
$k = 0;
for ($k=0; $k < $totalcount; $k++) {?>
start_year[<?php echo $k?>] =<?php echo $event_start_date[$k][0] ?>;
start_month[<?php echo $k?>] =<?php echo $event_start_date[$k][1] ?>;
start_day[<?php echo $k?>] =<?php echo $event_start_date[$k][2]?>;
end_year[<?php echo $k?>] =<?php echo $event_end_date[$k][0]?>;
end_month[<?php echo $k?>] =<?php echo $event_end_date[$k][1]?>;
end_day[<?php echo $k?>] =<?php echo $event_end_date[$k][2]?>;
start_hour[<?php echo $k?>] =<?php echo $event_start_time[$k][0] ?>;
start_mins[<?php echo $k?>] =<?php echo $event_start_time[$k][1] ?>;
end_hour[<?php echo $k?>] =<?php echo $event_end_time[$k][0]?>;
end_mins[<?php echo $k?>] =<?php echo $event_end_time[$k][1]?>;
<?php } ?>
var calendar = $('#calendar').fullCalendar({
editable: false,
events: [
<?php $j = 0;
for ($j=0; $j < $totalcount; $j++)
{
?>
<?php
if ($event[$j]['allday'] == 0){?>
{ title: '<?php echo $event[$j]['courseid'];?> <?php echo $event[$j]['coursename'];?>',
start: new Date(start_year[<?php echo $j?>],start_month[<?php echo $j?>]-1,start_day[<?php echo $j?>],start_hour[<?php echo $j?>],start_mins[<?php echo $j?>]),
end: new Date(end_year[<?php echo $j?>],end_month[<?php echo $j?>]-1,end_day[<?php echo $j?>],end_hour[<?php echo $j?>],end_mins[<?php echo $j?>]) , url: 'mg_course.php?courseid=<?php echo $event[$j]['courseid']; ?>'
/*
end: new Date(end_year[<?php echo $j?>],end_month[<?php echo $j?>]-1,end_day[<?php echo $j?>],end_hour[<?php echo $j?>],end_mins[<?php echo $j?>]) , url: 'mg_course.php?courseid=<?php echo $_GET['courseid']; ?>'
*/
},
<?php } ?>
<?php if ($event[$j]['allday'] == 1) {?>
{ title: '<?php echo $event[$j]['courseid'];?> <?php echo $event[$j]['coursename'];?>',
start: new Date(start_year[<?php echo $j?>],start_month[<?php echo $j?>]-1,start_day[<?php echo $j?>],start_hour[<?php echo $j?>],start_mins[<?php echo $j?>]),
end: new Date(end_year[<?php echo $j?>],end_month[<?php echo $j?>]-1,end_day[<?php echo $j?>],end_hour[<?php echo $j?>],end_mins[<?php echo $j?>]), url: 'mg_course.php?courseid=<?php echo $event[$j]['courseid']; ?>',
/*
end: new Date(end_year[<?php echo $j?>],end_month[<?php echo $j?>]-1,end_day[<?php echo $j?>],end_hour[<?php echo $j?>],end_mins[<?php echo $j?>]), url: 'mg_course.php?courseid=<?php echo $_GET['courseid']; ?>',
*/
allDay: 'false'
},
<?php } ?>
<?php }?>
{}
]
});
});
</SCRIPT>
<STYLE>BODY {
TEXT-ALIGN: center; MARGIN-TOP: 40px; FONT-FAMILY: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif; FONT-SIZE: 14px
}
#calendar {
MARGIN: 0px auto; WIDTH: 900px
}
</STYLE>
<META name=GENERATOR content="MSHTML 8.00.6001.19412"></HEAD>
<BODY>
<DIV id=calendar></DIV></BODY></HTML>
Here is display event details php:
<?php require_once('conn.php'); ?>
<?php
session_start();
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}
?>
<?php
$totalRows_RsEnrol = 0;
if ( isset($_POST['courseid']) ) {
$_GET['courseid'] = $_POST['courseid'];
$_GET['courseid'] = $_GET['courseid'] * 1;
if (is_integer($_GET['courseid']) ) {
$maxRows_RsEnrol = 10000;
$pageNum_RsEnrol = 0;
if (isset($_GET['pageNum_RsEnrol'])) {
$pageNum_RsEnrol = $_GET['pageNum_RsEnrol'];
}
$startRow_RsEnrol = $pageNum_RsEnrol * $maxRows_RsEnrol;
mysql_select_db($database_conn, $conn);
$query_RsEnrol = "SELECT * FROM 'tbl_enroll' WHERE 'tbl_enroll'.'courseid' = '".$_GET['courseid']."'";
//$query_RsEnrol = sprintf("SELECT erid, courseid, staffid FROM tbl_enroll WHERE courseid = %s ORDER BY staffid ASC", $_GET['courseid']);
$query_limit_RsEnrol = sprintf("%s LIMIT %d, %d", $query_RsEnrol, $startRow_RsEnrol, $maxRows_RsEnrol);
$RsEnrol = mysql_query($query_limit_RsEnrol, $conn) or die(mysql_error());
$row_RsEnrol = mysql_fetch_assoc($RsEnrol);
if (isset($_GET['totalRows_RsEnrol'])) {
$totalRows_RsEnrol = $_GET['totalRows_RsEnrol'];
} else {
$all_RsEnrol = mysql_query($query_RsEnrol);
$totalRows_RsEnrol = mysql_num_rows($all_RsEnrol);
}
$totalPages_RsEnrol = ceil($totalRows_RsEnrol/$maxRows_RsEnrol)-1;
} else { $totalRows_RsEnrol = 0;}
}
/******************************************************************************************************/
elseif (isset($_GET['courseid']) && !empty($_GET['courseid']) ) {
$_GET['courseid'] = $_GET['courseid']*1;
if (is_integer($_GET['courseid'])){
$maxRows_RsEnrol = 1000000;
$pageNum_RsEnrol = 0;
if (isset($_GET['pageNum_RsEnrol'])) {
$pageNum_RsEnrol = $_GET['pageNum_RsEnrol'];
}
$startRow_RsEnrol = $pageNum_RsEnrol * $maxRows_RsEnrol;
mysql_select_db($database_conn, $conn);
$query_RsEnrol = sprintf("SELECT * FROM tbl_enroll WHERE courseid IN ( SELECT courseid FROM tbl_course WHERE courseid = %s) ORDER BY erid ASC", $_GET['courseid']);
//$query_RsEnrol = sprintf("SELECT erid, courseid, staffid FROM tbl_enroll WHERE courseid=%s ORDER BY staffid ASC", $_GET['courseid']);
$query_limit_RsEnrol = sprintf("%s LIMIT %d, %d", $query_RsEnrol, $startRow_RsEnrol, $maxRows_RsEnrol);
$RsEnrol = mysql_query($query_limit_RsEnrol, $conn) or die(mysql_error());
$row_RsEnrol = mysql_fetch_assoc($RsEnrol);
if (isset($_GET['totalRows_RsEnrol'])) {
$totalRows_RsEnrol = $_GET['totalRows_RsEnrol'];
} else {
$all_RsEnrol = mysql_query($query_RsEnrol);
$totalRows_RsEnrol = mysql_num_rows($all_RsEnrol);
}
$totalPages_RsEnrol = ceil($totalRows_RsEnrol/$maxRows_RsEnrol)-1;
} else {$totalRows_RsEnrol=0;}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link href="../../css/style_new.css" rel="stylesheet" type="text/css" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<br />
<table width="322" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="171"><img src="../../Images/logo.gif" width="144" height="34"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center" ><h2>Training Program</h2></td>
</tr>
</table>
<div class="containers" align=">
<div class="header">
<p align="center" class="style2">Enrolment</p>
<h5 class="../css/new_style.css" align="left">
<table align="center" width="116%" border="0" cellpadding="0" cellspacing="2" >
<tr align="center" bgcolor="#CCCCCC" >
<td width="16%">Enrolment ID</td>
<td width="50%">Course ID</td>
<td width="14%">Staff ID</td>
<td width="10%"> </td>
<td width="10%"> </td>
</tr>
<tr align="center" bgcolor="#dfdfdf" >
<td><?php echo $row_RsEnrol['erid']; ?></td>
<td align="left"> <?php echo $row_RsEnrol['courseid']; ?></td>
<td><?php echo $row_RsEnrol['staffid']; ?></td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
It is unable to filter data on Calendar.
I am really appreciated for your help.

How to refresh a PHP Page without reload

I have a PHP page called js.php and i want to refresh the page without reloading the entire page. I know this question has been asked too many times but I just cant understand it. I tried the code below but its not working. And i also wanna ask, where is this code supposed to be placed in. js.php or another file?? Is there any other way of making the page refresh without reload? Its rather long but ultimately i want to refresh the page , specifically 2 variables , profittext and sumtext Please ignore the slash codes.
js.php
<?php
//error_reporting(0);//on if need
//require "core/init.php";
//protectpage();
$bidpricepl='';
$offerpricepl='';
$sum='';
$profitText =0;
$sumText=0;
?>
<!DOCTYPE html>
<html>
<head>
<h2>Trade Page</h2>
<script type="text/JavaScript">
<!--
//function timedRefresh(timeoutPeriod) {
//setTimeout("location.reload(true);",timeoutPeriod);
//}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(2000);">
<script>
function openWin()
{
myWindow=window.open('tradeform.php','pop','width=600,height=600');
myWindow.focus();
}
function openWin1()
{
myWindow=window.open('tradehistory.php','pop','width=1000,height=600');
myWindow.focus();
}
</script>
</head>
<body>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">User Name</th><th style="border:1px solid black;">Balance</th>
</tr>
<tr>
<td style="border:1px solid black;">Eg.SEYAN</td><td style="border:1px solid black;">Eg. 50000 </td>
</tr>
</table>
<input style="display:inline" type="button" value="Create New Order" onclick="openWin()" />
<input style="display:inline" type="button" value="Trade History" onclick="openWin1()" />
<link rel="stylesheet" type="text/css" href="truefxhp.css" />
<iframe src="http://webrates.truefx.com/rates/webWidget/trfxhp.jsp?c=EUR/USD,USD/JPY,USD/CAD,EUR/JPY,EUR/CHF,GBP/USD,AUD/USD,USD/CHF" width="400" height="400" seamless></iframe>
</body>
</html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">User Name</th><th style="border:1px solid black;">Balance</th><th style="border:1px solid black;">Equity</th>
</tr>
<tr>
<td style="border:1px solid black;">SEYAN</td><td style="border:1px solid black;">50000 </td><td style="border:1px solid black;">50000 </td>
</tr>
</table>
<?php
echo "<br>";
require_once 'connect.php';
include 'start.php';
include 'functions.php';
$query = "SELECT * FROM opentrades"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table border = '1px'>"; // start a table tag in the HTML
echo "<tr><td>" . "Order Number" . "</td><td>" . "Selection" . "</td><td>" . "Date" . "</td><td>" . "Type" . "</td><td>" . "Size" . "</td><td>" . "Bid Price" . "</td><td>" . "Offer Price" . "</td><td>" ."Stop Loss" . "</td><td>" . "Take Profit" . "</td><td>" ."Profit/Loss(USD)"."</td><td>" ."Close"."</td></tr>" ; //$row['index'] the index here is a field name
while($row = mysql_fetch_assoc($result)){ //Creates a loop to loop through results
if ($row['selection']=='eur/usd')// TO RETRIEVE BID AND OFFER FOR EACH ROW
{
$bidpricepl=$bid;
$offerpricepl=$bid1;
}
elseif ($row['selection']=='usd/jpy')
{
$bidpricepl=$bid2;
$offerpricepl=$bid3;
}
elseif ($row['selection']=='usd/cad')
{
$bidpricepl=$bid4;
$offerpricepl=$bid5;
}
elseif ($row['selection']=='eur/jpy')
{
$bidpricepl=$bid6;
$offerpricepl=$bid7;
}
elseif ($row['selection']=='eur/chf')
{
$bidpricepl=$bid8;
$offerpricepl=$bid9;
}
elseif ($row['selection']=='gbp/usd')
{
$bidpricepl=$bid10;
$offerpricepl=$bid11;
}
elseif ($row['selection']=='aud/usd')
{
$bidpricepl=$bid12;
$offerpricepl=$bid13;
}
elseif ($row['selection']=='usd/chf')
{
$bidpricepl=$bid14;
$offerpricepl=$bid15;
}
if ($row['type']=="buy")
{
//$last3charsoffer = substr($row['offerprice'], -6);
//$offernodecimal = str_replace('.', '', $last3charsoffer);
//$last3charsoffer1 = substr($offerpricepl, -6);
//$offernodecimal1 = str_replace('.', '', $last3charsoffer1);
//$pips2 = ltrim($pips2, '0');
//$calcpips2=$calcpips/$minipipskiller;
//$last3charsoffer = substr($row['offerprice'], -6);
//$offernodecimal = str_replace('.', '', $last3charsoffer);
//$last3charsoffer1 = substr($offerpricepl, -6);
//$offernodecimal1 = str_replace('.', '', $last3charsoffer1);
//$minipipskiller='10';
//$offeropen=$row['offerprice'];// to define variable
//$pips=$offerpricepl-$offeropen;// to calculate difference STEP 1
//$calcpips = str_replace('.', '', $pips); //removing the deci
//$calcpips = ltrim($calcpips, '0');// remove zeros in front
//$calcpips2=$calcpips/$minipipskiller;// to divide by 10 to cut mini pips
$minipipskiller='10';
$offeropen=$row['offerprice'];
$pips=$offerpricepl-$offeropen;
$closedb=$offeropen;
$pips1=round($pips, 6);
$pips2 = str_replace('.', '', $pips1);
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');
}
$pips3=$pips2/$minipipskiller;
}// PIP COUNTING
elseif ($row['type']=="sell")//FOR PIP COUNTING
{
//$last3charsbid = substr($row['bidprice'], -6);
//$bidnodecimal = str_replace('.', '', $last3charsbid);
//$last3charsbid1 = substr($bidpricepl, -6);
//$bidnodecimal1 = str_replace('.', '', $last3charsbid1);
$minipipskiller='10';
$bidopen=$row['bidprice'];
$pips=$bidopen-$bidpricepl;
$closedb=$bidopen;
$pips1=round($pips, 6);
$pips2 = str_replace('.', '', $pips1);
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');
}
$pips3=$pips2/$minipipskiller;
}
//echo $pips3;
$ticksize= "0.0001";// FOR PROFIT AND LOSS
$lot1 = "100000";
$sizecalc=$row['size'] * $lot1;
if ($row['type']=="buy")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
if ($row['type']=="sell")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
//echo $lot1;
//echo $ticksize;
$zero= '0';
//if($profitandloss<$zero){
// echo "<div style=\"color: red;\">$profitandloss</div>";
//}
//elseif ($profitandloss>$zero){
// echo "<div style=\"color: green;\">$profitandloss</div>";
//}
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
//$result_array = $codes->result_array();
//$results = array();
//$today = time();
//foreach($codes->result_array() as $row)
//{
// if(strtotime($row['exp_date']) <= $today)
// {//-- Keep this
// $results[] = $row;
//var allLinks = document.links;
// Bind the event handler to each link individually
//for (var i = 0, n = allLinks.length; i < n; i++) {
//allLinks[i].addEventListener('click', function (event) {});
// allLinks[i].onclick = function () {
// Do something
?>
JavaScript
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
$(document).ready(function() {
var reloadData = 0; // store timer
load data on page load, which sets timeout to reload again
loadData();
});
function loadData() {
$('#load_me').load('js.php', function() {
if (reloadData != 0)
window.clearTimeout(reloadData);
reloadData = window.setTimeout(loadData, 1000)
}).fadeIn("slow");
}
</script>
</head>
<body>
<div id="load_me"></div>
</body>
</html>
You can keep this code in Js.php
If you are not getting desired results, t## en you can try filrebug and chjeck for any javascript errors using ctr+shift+j
Or else use iframe.
There is an error in your page which will prevent the script from workin
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
$(document).ready(function() {
var reloadData = 0; // store timer
// ----- load data on page load, which sets timeout to reload again
loadData();
});
function loadData() {
$('#load_me').load('js.php', function() {
if (reloadData != 0)
window.clearTimeout(reloadData);
reloadData = window.setTimeout(loadData, 1000)
}).fadeIn("slow");
}
</script>
</head>
<body>
<div id="load_me"></div>
</body>
</html>
See the line marked // -----
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
function loadData() {
$('#load_me').load('js.php', function() {
if (window.reloadData != 0)
window.clearTimeout(window.reloadData);
window.reloadData = window.setTimeout(loadData, 1000)
}).fadeIn("slow");
}
window.reloadData = 0; // store timer load data on page load, which sets timeout to reload again
loadData();
});
</script>
</head>
<body>
<div id="load_me"></div>
</body>
</html>
Its because your ajax request going to same page.
You can send ajax to other php(test.php) file
In test.php just generate content you want to show in your div
<div id="load_me">
$data
</div>
just echo $data
and exit.
change $('#load_me').load('test.php', function().....
You need to use ajax for that use jquery load function for this Check here
Simply use AJAX (Asynchronous JavaScript And XML). Click here for more info
You not able to use PHP for specifiec parts of page, without refreshing full page

Categories