I have installed a jquery UI tabs system on my web page , but the I have had a series of problems , one of them being: I can make a form request to my PhP at the same page and then process the result on it self.
In other words: I want to set the action of the form in question to the the same tab, loaded from another file via ajax, that contains the form in the first place, so it can read and display a table with the search results.
Here are some codes, hope it helps.
The index (continas the #tabs div):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1" />
<link type="text/css" href="css/smoothness/jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<link rel="stylesheet" type="text/css" href="css.css"></link>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="maskMoney.js"></script>
<title>Financeiro</title>
</head>
<body>
<script>
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"A tab não pode ser carregada ou está sob manutenção, desculpe o transtorno." );
}
}
});
});
</script>
<div>
<div id="tabs">
<ul>
<li>Buscar saída</li>
<li>Criar saída</li>
</ul>
</div>
</div>
<script type="text/javascript" src="create.js"></script>
</body>
</html>
And here it is one of the forms I place under a tab (the financeiro_ver.php file):
<?php
include 'all.php';
if (isset($_POST['efetuar'])) {
$saida = new Saida();
if (isset($_POST['situacao'])) {
$saida->situacao = $_POST['situacao'];
} else {
$saida->situacao = 'npago';
}
$sql = "UPDATE financeiro SET situacao = '".$saida->situacao."' WHERE id = '".$_POST['saidaId']."'";
mysql_query($sql);
}
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['ID_FUNCIONARIO'] = 46;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1" />
<link type="text/css" href="css/smoothness/jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<link rel="stylesheet" type="text/css" href="css.css"></link>
<title>Financeiro</title>
</head>
<body>
<form id="form0" name="form0" method="post" action="financeiro_ver.php"> <!--action="http://sim.medgoldman.com.br/financeiro/financeiro_ver.php" style="background-color:#EEEEEE"> -->
<table border="0" align="center" cellpadding="10" cellspacing="0">
<tr>
<td align="center">GRUPO:
<select name="categoria" id="produto">
<option value="adm">Despesas Administrativas</option>
<option value="imp">Importações</option>
<option value="ban">Bancos</option>
<option value="matriz">Despesas Matriz</option>
<option value="outros">Outros</option>
</select></td>
<td align="center">PERÍODO:
<td>de: <input name="data1" id="data1" value=""></input></td>
<td>até: <input name="data2" id="data2" value=""></input></td>
</select></td>
<td align="center"><input name="buscar" type="submit" id="buscar" value=" Buscar " /></td>
</tr>
</table>
</form>
<?php
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
echo '<form name="form2" method="post" <!--action="http://sim.medgoldman.com.br/financeiro/financeiro_ver.php" --> style="background-color:#EEEEEE">';
}
?>
<table class ="viewTable" align="center">
<?php
if (isset($session->message)) {
$mens ="<th>" . $session->message . "</th>";
echo utf8_encode($mens);
}
if (isset($_POST['buscar'])) {
$query = "SELECT * FROM financeiro " .
"WHERE categoria = '" . $_POST['categoria'] .
"' AND data >= '" . $_POST['data1'] .
"' AND data <= '" . $_POST['data2'] . "'";
if (mysql_query($query, $database->connection)) {
$categoriaSel = mysql_query($query, $database->connection);
$output = '<tr><th colspan="3">Categoria ';
if ($_POST['categoria'] === 'adm') {
$output .= "Despesas administrativas";
} elseif ($_POST['categoria'] === 'imp') {
$output .= "Importações";
} elseif ($_POST['categoria'] === 'ban') {
$output .= "Bancos";
} elseif ($_POST['categoria'] === 'outros') {
$output .= "Outros";
} elseif ($_POST['categoria'] === 'matriz') {
$output .= "Despesas Matriz";
}
$output .= "</th>";
$output .= "<tr><th>Data</th><th>Descrição</th><th>Valor</th></tr>";
$valorSomaUS = 0;
$valorSomaRS = 0;
while ($saidasSel = mysql_fetch_array($categoriaSel)) {
$valorDisplay = number_format($saidasSel['valor'], '2', ',', '.');
$output .= "<tr";
if ($saidasSel['situacao'] === 'pago') {
$output .= ' class="pago"';
} else if ($saidasSel['situacao'] === 'npago') {
$output .= ' class="npago"';
}
$output .= ">";
$output .= "<td class=\"datout\">" . $saidasSel['data'] . "</td>";
$output .= "<td class=\"desout\">" . $saidasSel['descricao'] . "</td>";
if ($saidasSel['cambio'] === "us") {
$output .= "<td class=\"valout\"> U$ " . $valorDisplay . "</td>";
$valorSomaUS += $saidasSel['valor'];
} else {
$output .= "<td class=\"valout\"> R$ " . $valorDisplay . "</td>";
$valorSomaRS += $saidasSel['valor'];
}
//VERIFICA USUARIO PARA ADICIONAR PAGO/NPAGO:
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
$output .= '<td><input name="situacao" type="checkbox" value="pago"';
if ($saidasSel['situacao'] === 'pago') {
$output .= ' checked';
}
$output .=">Pago</input></td>";
}
//VERIFICA USUARIO PARA VER PAGO/NPAGO:
if ($_SESSION['ID_FUNCIONARIO'] == '46') {
if ($saidasSel['situacao'] === 'pago') {
$output .= '<td>pago</td>';
} else {
$output .= '<td>não pago</td>';
}
}
if ($_SESSION['ID_FUNCIONARIO'] == '30' && $saidasSel['categoria'] === "imp") {
if ($saidasSel['situacao'] === 'pago') {
$output .= '<td>pago</td>';
} else {
$output .= '<td>não pago</td>';
}
}
//VERIFICA USUARIO PARA ADICIONAR DELETAR:
if (($_SESSION['ID_FUNCIONARIO'] == '46') && ($saidasSel['categoria'] === 'adm' || $saidasSel['categoria'] === 'outros' || $saidasSel['categoria'] === 'matriz')) {
$output .= "<td><button class=\"deletar\" href=\"financeiro_deletar.php?id=" . $saidasSel['id'] . "\">Deletar</button>";
} elseif (( $_SESSION['ID_FUNCIONARIO'] == '30' || $_SESSION['ID_FUNCIONARIO'] == '46' ) && $saidasSel['categoria'] === 'imp') {
$output .= "<td><button class=\"deletar\" href=\"financeiro_deletar.php?id=" . $saidasSel['id'] . "\">Deletar</button></td>";
}
$output .="</tr>";
//SOMA DOS VALORES DO PERIODO:
$valorSomaUS = number_format($valorSomaUS, '2', ',', '.');
$valorSomaRS = number_format($valorSomaRS, '2', ',', '.');
$output .= "<tr> <td class=\"valsoma\" colspan=\"3\"> Soma do período = R$ " . $valorSomaRS . " e U$ " . $valorSomaUS . "</td></tr>";
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
$output .= '<tr><td><input id="efetuar" type="submit" value=" Efetuar " name="efetuar"></input></td><td><input type="hidden" value="' . $saidasSel['id'] . '" name="saidaId"></input></td></tr>';
}
}
echo utf8_encode($output);
} else {
$session->message("Nenhuma saída para este período.");
}
}
?>
</table>
<?php
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
echo '</form>';
}
?>
</body>
</html>
http://jsfiddle.net/mZLDk/
$(document).ready(function() {
// Tab initialization
// This is setup for two tab groups and is not needed
$('#tabs, #fragment-1').tabs({
select: function(event, ui){
var tabNumber = ui.index;
var tabName = $(ui.tab).text();
//Here I setup an event for each change this changes some inner html
//of a tag but can be applied in your situation
if(tabNumber = 1 ) {
document.getElementById('fragment-1a').innerHTML = "changed";
} else {
}
//This was just some debuging code for me
console.log('Tab number ' + tabNumber + ' - ' + tabName + ' - clicked');
}
});
});
You would replace the line
document.getElementById('fragment-1a').innerHTML = "changed";
with
document.forms[0].action = "An Action";
Im really excited as this is my first working answer for some one on this site so please tell me if it works
THE BIG LONG STORY OF HOW A COMPLETE JAVASCRIPT NOOB FOUND YOUR ANSWER
As an idea you could try making it so the tabs event changes the setting IE this
jQuery - trapping tab select event
but how does that apply to you well I found something else here
http://www.tek-tips.com/viewthread.cfm?qid=1235640
this talks about chagines a form action based uppon an event which you can change onlcick.
But now an example that brings the two together
http://jsfiddle.net/mZLDk/
Related
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!
here I am going to delete the database record, when i delete the record, the record deletes successfully but it dosen't reload the insert_search page it displays the result and deleted result will not go, so i need to type every time insert_search in url to get the updated result, please can u tell me where i need to reload the page and how to implement it, thank you in advance...
<?php
$user = "root";
$server = "localhost";
$password = "";
$db = "coedsproddb1";
$dbconn = mysql_connect($server, $user, $password);
mysql_select_db($db, $dbconn);
?>
<html>
<head>
<title>Insert</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
#display {
color: red;
font-size: 12px;
text-align: center;
}
.logo {
padding: 5px;
float: left;
}
header {
background-color: #074e7c;
height: 60px;
width: 100%;
text-align: center;
color: white;
font-size: 40px;
}
#wrap {
text-align: center;
}
</style>
</head>
<body>
<header><img src="images/ipoint.png" class="logo" /> USER REGISTRATION</header>
<div class="container">
<h1 style="text-align:center">ADDING THE USER DETAILS</h1>
<form name="useradd" id="useradd" action="#" method="post">
<table align='center' border='1'>
<tr>
<td>
<label for="userName">UserName</label>
</td>
<td>
<input id="userName" name="userName" type="text" />
</td>
</tr>
<tr>
<td>
<label for="userEmail">Email</label>
</td>
<td>
<input id="userEmail" name="userEmail" type="text" />
</td>
</tr>
<tr>
<td>
<label for="userPassword">password</label>
</td>
<td>
<input id="userPassword" name="userPassword" type="password" />
</td>
</tr>
</table>
<br>
<div id="wrap">
<input type="submit" name="add" value="add" id="add">
<input type="submit" name="update" value="update" id="update">
</div>
</form>
<div id="display">
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(e) {
var userName = $("#userName").val();
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var dataString = 'userName=' + userName + '&userEmail=' + userEmail + '&userPassword=' + userPassword;
alert(dataString);
if (userName == "" || userEmail == "" || userPassword == "") {
document.getElementById("display").innerHTML = "Please Enter The Fields";
} else if (!validate1($.trim(userName))) {
document.getElementById("display").innerHTML = "Please Enter The Valid UserName";
document.getElementById("display").focus();
} else if (!ValidateEmail($.trim(userEmail))) {
document.getElementById("display").innerHTML = "Please Enter The Valid Emailid";
document.getElementById("display").focus();
} else {
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(result) {
//alert("submitted"+result);
$('#display').html(result);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
e.preventDefault();
});
function validate1(userName) {
var u = userName;
var filter = /^[a-zA-Z0-9]+$/;
if (filter.test(u)) {
return true;
} else {
return false;
}
}
function ValidateEmail(userEmail) {
var e = userEmail;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (filter.test(e)) {
return true;
} else {
return false;
}
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#update").click(function(e) {
alert("hi");
var userName = $("#userName").val();
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var dataString = 'userName=' + userName + '&userEmail=' + userEmail + '&userPassword=' + userPassword;
alert(dataString);
if (userEmail == "" || userPassword == "") {
document.getElementById("display").innerHTML = "Please Enter The Fields";
} else {
$.ajax({
type: "POST",
url: "user_update.php",
data: dataString,
cache: false,
success: function(result) {
//alert("submitted"+result);
$('#display').html(result);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
e.preventDefault();
});
});
</script>
</body>
</html>
insert.php
<html>
<head>
<title>Insertion</title>
</head>
<body>
<div id="display">
<?php
include('db.php');
$userName = mysql_real_escape_string($_POST['userName']);
$userEmail = mysql_real_escape_string($_POST['userEmail']);
$userPassword = mysql_real_escape_string($_POST['userPassword']);
$regDate = date("Y-m-d");
function generateCode($characters)
{
$possible = '23456789abcdefghjkmnpqrstuvwxyz';
$code = '';
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible) - 1), 1);
$i++;
}
return $code;
}
$registration_key = generateCode(10);
$str = "insert into coeds_user(userName,userEmail,userPassword,regDate,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$registration_key')";
echo $str;
$query = mysql_query($str);
if ($query) {
$display = "Success";
} else {
$display = "Failed";
}
$string = "select * from coeds_user";
$query2 = mysql_query($string);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>RegistrationKey</th></tr>";
while ($result = mysql_fetch_array($query2)) {
$display .= "<tr>";
$display .= "<td>" . $result['userId'] . "</td>";
$display .= "<td>" . $result['userName'] . "</td>";
$display .= "<td>" . $result['userEmail'] . "</td>";
$display .= "<td>" . $result['userPassword'] . "</td>";
$display .= "<td>" . $result['regDate'] . "</td>";
$display .= "<td>" . $result['registration_key'] . "</td>";
$display .= "<td><a href='user_update.php?user_Id=" . $result['userId'] . "'>Edit</a></td>";
$display .= "<td><a href='user_delete.php?user_Id=" . $result['userId'] . "'>Delete</a></td>";
$display .= "</tr>";
}
$display .= "</table>";
location . reload();
echo $display;
?>
</div>
</body>
</html>
user_delete.php
<html>
<head>
<title>Deletion</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
#display {
color: red;
font-size: 12px;
text-align: center;
}
.logo {
padding: 5px;
float: left;
}
header {
background-color: #074e7c;
height: 60px;
width: 100%;
text-align: center;
color: white;
font-size: 40px;
}
#wrap {
text-align: center;
}
</style>
</head>
<body>
<header> <img src="images/ipoint.png" class="logo" /> USER REGISTRATION</header>
<div class="container">
<h1 style="text-align:center">DELETE WINDOW</h1>
<div id="display">
<?php
include('db.php');
if (isset($_GET['user_Id'])) {
$userid = $_GET['user_Id'];
}
?>
<form action="user_delete.php" name="user_delete" method="post">
<input type="hidden" name="user_Id" id="user_Id" value="<?php
if (isset($userid))
echo $userid;
?>">
<?php
include('db.php');
$s = "delete from coeds_user where userId=$userid";
$query3 = mysql_query($s);
if ($query3) {
$display = "Delete Is Successful";
} else {
$display = "Delete Is Unsuccessful";
}
$string = "select * from coeds_user";
$query5 = mysql_query($string);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegistrationDate</th><th>RegistrationKey</th></tr>";
while ($res1 = mysql_fetch_array($query5)) {
$display .= "<tr>";
$display .= "<td>" . $res1['userId'] . "</td>";
$display .= "<td>" . $res1['userName'] . "</td>";
$display .= "<td>" . $res1['userEmail'] . "</td>";
$display .= "<td>" . $res1['userPassword'] . "</td>";
$display .= "<td>" . $res1['regDate'] . "</td>";
$display .= "<td>" . $res1['registration_key'] . "</td>";
}
echo $display;
?>
</div>
</form>
</div>
</body>
</html>
user_update.php
<html>
<head>
<title>Updation</title>
</head>
<body>
<div id="display">
<?php
include('db.php');
if (isset($_GET['user_Id'])) {
$userid = $_GET['user_Id'];
echo $userid;
$s = "select * from coeds_user where userId=$userid";
echo $s;
$query1 = mysql_query($s);
$res = mysql_fetch_array($query1);
?>
<input type="hidden" name="userPassword" id="userPassword">
<input type="hidden" name="userEmail" id="userEmail">
<form action="user_update.php" name="user_update" method="post">
<input type="hidden" name="user_Id" id="userId" value="<?php
if (isset($userid))
echo $userid;
?>">
<table align='center' border='1'>
<tr>
<td>
<label for="userName">UserName</label>
</td>
<td>
<input id="userName" name="userName" type="text" value="<?php
echo $res['userName'];
?> " />
</td>
</tr>
<tr>
<td>
<label for="userEmail">Email</label>
</td>
<td>
<input id="userEmail" name="userEmail" type="text" value="<?php
echo $res['userEmail'];
?> " />
</td>
</tr>
<tr>
<td>
<label for="userPassword">password</label>
</td>
<td>
<input id="userPassword" name="userPassword" type="password" value="<?php
echo $res['userPassword'];
?> " />
</td>
</tr>
</table>
<input type="submit" name="modify" id="modify" value="modify">
<?php
}
include('db.php');
if (isset($_POST['user_Id'])) {
$userid = $_POST['user_Id'];
echo $userid;
}
if (isset($_POST['modify'])) {
echo $userid;
$userName = mysql_real_escape_string($_POST['userName']);
$userEmail = mysql_real_escape_string($_POST['userEmail']);
$userPassword = mysql_real_escape_string($_POST['userPassword']);
$string = "update coeds_user set userName='$userName',userEmail='$userEmail', userPassword='$userPassword' where userId=$userid";
echo $string;
$query = mysql_query($string);
if ($query) {
$display = "Update Successful";
} else {
$display = "Update Failed";
}
$s = "select * from coeds_user";
$query = mysql_query($s);
$display .= "<table border='1'>";
$display .= "<tr><th>UserId</th><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>RegistrationKey</th></tr>";
while ($res = mysql_fetch_array($query)) {
$display .= "<tr>";
$display .= "<td>" . $res['userId'] . "</td>";
$display .= "<td>" . $res['userName'] . "</td>";
$display .= "<td>" . $res['userEmail'] . "</td>";
$display .= "<td>" . $res['userPassword'] . "</td>";
$display .= "<td>" . $res['regDate'] . "</td>";
$display .= "<td>" . $res['registration_key'] . "</td>";
$display .= "</tr>";
}
$display .= "</table>";
echo $display;
}
?>
</div>
</body>
</form>
</html>
Use
echo "<script>location.replace('user_delete.php');</script>";
instead of header location.
Hope this helps.
I made a simple table math calculator.
Only now I want when you echo the number the ODD numbers are red and the even numbers display green.
Is this possible with css ? or do I have to rebuild the whole code ?
Code HTML + PHP
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<center>
<form action = "pagina2.php" method = "post">
<input name = "invoer" type = "text" value = "">
<input name = "knop" type = "submit" value = "Verstuur">
</form>
</center>
</body>
</html>
//PHP
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<center>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['invoer']))
{
if (is_numeric($_POST['invoer']))
{
for ($i = 1; $i <= 10; $i++)
{
echo $i . " x " . $_POST['invoer'] . " = " . ($i * $_POST['invoer']) . "<br />";
}
}
else
{
echo "Vul een getal in!";
}
}
else
{
echo "Niks ingevoerd!";
}
}
?>
</center>
<br>
<center>
<input action="action" type="button" value="Opnieuw" onclick="history.go(-1);" />
</center>
</body>
</html>
Greetings.
Change this echo statment
echo $i . " x " . $_POST['invoer'] . " = " . ($i * $_POST['invoer']) . "<br />";
To
$x=$i . " x " . $_POST['invoer'] . " = " . ($i * $_POST['invoer']) . "<br />";
if($x % 2 ==0 )
{
echo '<font color="green">'.$x.'</font>';
}
else echo '<font color="red">'.$x.'</font>';
I would use modulas to shorten your code
$number % 2 == 0 #means even
Then use a css class like .odd or .even and inject that into your template
I assume you are referring to the variable $i:
echo '<div style="color: '.($i%2==0 ? 'green' : 'red').">". $i . " x " . $_POST['invoer'] . " = " . ($i * $_POST['invoer']) . "</div><br />";
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
I am having a problem with pagination within the tabs. In the second tab (candidate), when I press pagination 2 to navigate to the second page of the candidate table, I am returned to the first page of the contact table. If I go to the candidate tab after that I am on the right page. Where have I gone wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/start/jquery-ui.css"/>
<link type ="text/css" rel ="stylesheet" href = "testData.cs"/>
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
});
</script>
<head>
<title>Candidate DB</title>
</head>
<body>
<div id ="tabs1" class ="contactForm">
<ul>
<li>List of Contacts</li>
<li>List of Candidates</li>
<li>Advanced Search</li>
</ul>
<div id ="tab1" class="contact" >
<table border="1" id="contact_info">
<tr>
<th>Contact Name</th>
<th>County</th>
</tr>
<?php
$DB_NAME = "Candidate";
$DB_USER ="root";
$DB_PASSWORD ="";
$DB_HOST ="localhost";
$con=mysql_connect("$DB_HOST", "$DB_USER", "$DB_PASSWORD") or die("Could not connect to MySQL");
mysql_select_db("$DB_NAME") or die ("No Database");
echo "Connected to Candidate Database </br></hr>" ;
$per_page=5;
$pages_query= mysql_query("SELECT COUNT(contact_id) FROM contact");
$pages = ceil(mysql_result($pages_query,0)/$per_page);
$page=(isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start=($page-1) * $per_page;
$sql=mysql_query("SELECT first_name, last_name, county from contact ORDER BY last_name ASC LIMIT $start, $per_page" );
$Fname = 'first_name';
$Lname = 'last_name';
$county = 'county';
while ( $row = mysql_fetch_object($sql)) {
echo "<tr>";
echo "<td>" . $row ->first_name . " " . $row->last_name. "</td>";
echo "<td>" . $row->county . "</td>";
echo "</tr>";
}
// close the loop
if ($pages>=1 && $page<= $pages ) {
for ($x=1; $x<=$pages; $x++)
{
echo ($x ==$page)? '<strong><a style="color:green" href="? page='.$x.'">'.$x. '</a></strong>_':''.$x. '_';
}
}
?>
</table>
</div>
<div id ="tab2" class="candidate" >
<table border="1" id="candidate_info">
<tr>
<th>Candidate Name</th>
<th>County</th>
</tr>
<?php
$per_pageR=5;
$pages_queryR= mysql_query("SELECT COUNT(candidate_id) FROM p_candidate");
$pagesR = ceil(mysql_result($pages_queryR,0)/$per_pageR);
$pageR=(isset($_GET['pageR'])) ? (int)$_GET['pageR'] : 1;
$startR=($pageR-1) * $per_pageR;
$sql2=mysql_query("SELECT R_first_name, R_last_name, R_county from p_candidate ORDER BY R_last_name ASC LIMIT $startR, $per_pageR" );
$R_name = 'R_first_name';
$R_name = 'R_last_name';
$R_county = 'R_county';
while ( $rowR = mysql_fetch_object($sql2)) {
echo "<tr>";
echo "<td>" . $rowR ->R_first_name . " " . $rowR->R_last_name. "</td>";
echo "<td>" . $rowR->R_county . "</td>";
echo "</tr>";
}
// close the loop
if ($pagesR>=1 && $pageR<= $pagesR ) {
for ($y=1; $y<=$pagesR; $y++)
{
echo ($y ==$pageR)? '<strong><a style="color:green" href="? pageR='.$y.'">'.$y. '</a></strong>_':''.$y. '_';
}
}
?>
</table>
</div>
</div>
</body>
If I understand correctly, try using the active option - http://api.jqueryui.com/tabs/#option-active - when you do .tabs() to make the candidate tab the active tab.
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo "{ active: 1 }"; ?>);
});
</script>
or
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo '"option", "active", -1'; ?>);
});
</script>
edit
You could bind the .tabs() first, and then set the active option. This should hopefully fix your formatting issue.
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
<?php if(isset($_GET['pageR'])) { ?>
$('#tabs1').tabs("option", "active", -1)
<?php } ?>
});
</script>