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
Related
I load data onto a page using Ajax.
Here is the div (saleContentData) into which it is loaded:
<div class="resultsPage salesList">
<h2>Sales</h2>
<div class="salesFilters">
<form action="" method="POST">
<label for="date1">Start Date</label>
<input id="startDate" type="date" name="date1" value="Start Date" placeholder="Start Date" value="" min="1997-01-01" max="2030-12-31" />
<label for="date2">End Date</label>
<input id="endDate" type="date" name="date2" value="End Date" placeholder="End Date" value="" min="01-01-2010" max="01-01-2030" />
<button id="filterSales">Filter Sales</button>
<button id="resetFilter">Reset</button>
</form>
</div>
<div class=" salesContent">
<div class="saleContentData">
<div id="loading">
<img id="loading-image" src="assets/img/loader.gif" alt="Loading..." />
</div>
</div>
</div>
</div>
Here is the the script to display the data.
if (isset($_POST['start_date']) && $_POST['end_date']) {
$startDate = $_POST['start_date'];
$endDate = $_POST['end_date'];
$page_size = $_POST['page_size'];
$page_num = $_POST['page_num'];
showFiltered($startDate, $endDate, $page_size, $page_num);
} else if (isset($_POST['page_size']) && $_POST['page_num']) {
$page_size = $_POST['page_size'];
$page_num = $_POST['page_num'];
showNormal($page_size, $page_num);
} else {
showNormal();
}
function showNormal($page_number = 1, $page_size = 100)
{
//THE DATA
$data = getData("https://api.someapi.com/v2/sales?page_size=" . $page_size . "&page_number=" . $page_number);
//SHOW THE DATA
showRecords($data);
}
function showRecords($data)
{
//STATISTICS ABOUT THE DATA
$total_sales = ($data['page_summary']['total']);
$current_page = $data['page_summary']['page_number'];
echo $total_sales . " sales<br/>";
$num_pages = (ceil($total_sales / 100) * 100) / 100;
echo "<ul>";
// TO DISPLAY THE NUMBER OF PAGES
for ($page = 0; $page < $num_pages; $page++) {
if ($page == $current_page - 1) {
echo "<li class='page$page active'>" . $page + 1 . "</li>";
} else {
echo "<li class='page$page'>" . $page + 1 . "</li>";
}
}
echo "</ul>";
// TABLE WITH ALL SALES RECORDS
$sales = $data['sales'];
$counter = 1;
echo "<table id='salesTable'>
<thead><tr class='headingRow'><th class='image'></th><th class='productHD'>Product</th><th>Status</th><th>Revenue</th><th>Quantity</th><th class='dcCol'>DC</th><th>Order ID</th><th>Customer Name</th><th>Date</th></tr></thead>";
foreach ($sales as $key => $row) {
$col1 = $row['selling_price'];
$col2 = $row['quantity'];
$revenue = ($col1 * $col2);
echo "<tr><td class='num centerCol'><img src='placeholder.png'/></td><td class='productTitle'>" . $row['product_title'] . "</td><td class='centerCol'>" . $row['sale_status'] . "</td><td class='centerCol'>" . "R" . $revenue . "</td><td class='centerCol'>" . $row['quantity'] . "</td><td class='centerCol'>" . $row['dc'] . "</td><td class='centerCol'>" . $row['offer_id'] . "</td><td>" . $row['customer'] . "</td><td>" . $row['order_date'] . "</td></tr>";
}
echo "</table>";
}
Here is the Javscript that loads the page into the div:
$(".goSale").click(function () {
$.ajax({
method: "GET",
url: "getsales.php",
success: function (data) {
$(".saleContentData").html(data);
},
error: function (request, status, error) {
$(".saleContentData").html(error);
},
complete: function () {},
});
});
if I run the file by itself the list with the page numbers is displayed correctly and I see 1 TO 7. If I load the file using Ajax I get a different result and the page numbers are displayed as seven 1s.
Why would this be please?
So after looking at the HTML I see the list is not being generated and the numbers are loaded in the tag and so there is not list items.
Why would that be?
Does Ajax remove something?
Loading the page by itself
Loading the page using Ajax
Solved it:
echo "<ul id='pagesList'>";
for ($page = 0; $page < $num_pages; $page++) {
echo "<li class='page$page'>";
echo $page + 1;
echo "</li>";
}
echo "</ul>
The problem might be that you did not send any data to getsales.php page.
Check something like this.
How to send multiple data fields via Ajax?
If script you showed for displaying data is getsales.php, then you need to send there some data as below via ajax.
if (isset($_POST['start_date']) && $_POST['end_date']) {
$startDate = $_POST['start_date'];
$endDate = $_POST['end_date'];
$page_size = $_POST['page_size'];
$page_num = $_POST['page_num'];
}
showFiltered($startDate, $endDate, $page_size, $page_num);
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!
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.
I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!
Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>
Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});
I would like to ask for help on how to implement mouseover to checkbox. What I wan't to achieve is that I want to have mouseover when someone point the cursor to the checkbox based on subject description.
Below is my code to generate dynaminc checkbox but I don;t know how to add mouseover to it. thanks.
<?php
$subjects = $stmt->prepare("SELECT * FROM subjects");
$stmt->execute();
$cols = 5;
do
{
echo "<tr>";
for ($i = 1; $i <= $cols; $i++)
{
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row)
{
$sub_id = $row['sub_id'];
$sub_name = $row['sub_name'];
$sub_desc = $row['sub_desc']
?>
<table>
<tr><td>
<?php
echo '<input type="checkbox" sub_id="sub_id[]" name="sub_id[]" value="' . $id_tag . "\"" .'/>' . $tag_name . "\n";
?>
</td></tr>
</table>
<?php
} else {
echo "<td> </td>";
}
}
} while ($row);
?>
When you generate the HTML, you add a CSS class. And then, in your stylesheet, you define a hover effect. Like this:
echo '<input type="checkbox" class="HoverOnCheckbox" sub_id="sub_id[]" name="sub_id[]" value="'
.HoverOnCheckbox{
color:green;}
.HoverOnCheckbox:hover{
color:red;}
<script type="text/javascript">
function myfn() {
var myInput = event.target;
myInput.style.fontSize = "1.2em";
//some else...
}
</script>
<?php
echo '<input type="checkbox" onmouseover="myfn();" title="'.$row['sub_desc'].'" sub_id="sub_id[]" name="sub_id[]" value="' . $id_tag . "\"" .'/>' . $tag_name . "\n";
?>
There's many way to attach events in JavaScript. Another implement is using CSS.
<style type="text/css">
input:hover { font-size:1.2em; }
</style>
$(function() {
$('input[type="checkbox"]').each(function() {
$(this).hover(function(){
//mouseover effect
},function(){
//mouseout effect
});
});
});
EDIT: as #Repox suggested this will work with jquery