Displaying Results of inputbox in a table using php ajax jquery - php

I am trying to submit information to a mysql database. When the page loads it should show all the data currently in the mysql table and when the user enters the information it should update the table without refreshing the page. Here is what i have so far.
for my homepage
<body>
<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" typer="text/javascript"></script>
<div class="wrapper">
<h3>Conversation Portal</h3>
<div class="entry_wrapper">
<h4> Enter Conversation Here</h4>
<ul>
<li>
<label>English:</label>
<input class="inputbox" type="text" size="50" id="english"/>
</li>
<li>
<label>Sanskrit:</label>
<input class="inputbox" type="text" size="50" id="sanskrit"/>
</li>
<li>
<label>Date:</label>
<input class="inputbox" type="text" size="50" id="datepicker"/>
</li>
</ul>
</div>
<div class="response_wrapper">
<textarea id="responseText"></textarea>
</div>
<input type="button" value="submit" id="call_bck_btn"/>
</div>
</body>
For my javascript i have:
$(document).ready(function(){
$('#call_bck_btn').click(function(){
$.post("ajax.php" ,
{
english :$('#english').val(),
sanskrit :$('#sanskrit').val()
},
function(data)
{
$('#responseText').val(data);
}
);
});
});
And for my php:
<?php
$method=$_SERVER['REQUEST_METHOD'];
if(strtolower($method)=='post')
{
$english = addslashes($_POST['english']);
$sanskrit = addslashes($_POST['sanskrit']);
$connect=mysql_connect('localhost','root','');
$db=mysql_select_db('test2');
$sql="insert into conversation(English,Sanskrit) values('$english','$sanskrit')";
$result=mysql_query("select*from conversation");
echo "<table border='1'>
<tr>
<th>English</th>
<th>Sanskrit</th>
</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['English'] . "</td>";
echo "<td>" . $row['Sanskrit'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
Thanks for any ideas on what to do.

Well, your pretty much there with what you want. If you ran this, I think it would work (roughly). Although there are quite a few (major!) flaws in your code. Just to sum them up first:
Don't use root access to your database, EVER!! This is a MAJOR security hazard.
Don't use the mysql extension, it has officially been deprecated for several PHP versions now; instead use either PDO or MySQLi (both are far better)
Use prepared queries (available in PDO and MySQLi) to make your queries safer.
Fix your HTML; Don't display your resulting HTML table inside a tag. This is incorrect HTML. Rather, use a div for such a thing. Likewise,
In short, I would rewrite it to:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<h4> Enter Conversation Here</h4>
<form id="conversationForm">
<ul>
<li>
<label>English:</label>
<input class="inputbox" type="text" size="50" id="english"/>
</li>
<li>
<label>Sanskrit:</label>
<input class="inputbox" type="text" size="50" id="sanskrit"/>
</li>
<li>
<label>Date:</label>
<input class="inputbox" type="text" size="50" id="datepicker"/>
</li>
</ul>
</div>
<input type="button" value="submit" id="call_bck_btn"/>
</form>
<div id="resultTbl">
</div>
</body>
</html>
script.js:
$(function() {
$('#conversationForm').submit(function(e) {
$.post('ajax.php', $(this).serializeArray(), function(data, status, jqXHR) {
$('.resultTbl').html(data);
});
});
});
ajax.php:
<?php
if( (isset($_POST['english']) && strlen($_POST['english']) > 0) && (isset($_POST['sanskrit']) && strlen($_POST['sanskrit']) > 0) ) {
$mysqli = new mysqli('localhost','username','password', 'test2');
if($stmt = $mysqli->prepare("INSERT INTO `conversation` (English, Sanskrit) VALUES (?,?)")) {
$stmt->bind_param('ss', $_POST['english'], $_POST['sanskrit']);
$stmt->execute();
}
$result = $mysqli->query("SELECT English, Sanskrit FROM `conversation`", MYSQLI_STORE_RESULT);
echo '<table>';
while($row = $result->fetch_array()) {
echo '<tr>';
echo '<td>', $row['English'], '</td>';
echo '<td>', $row['Sanskrit'], '</td>';
echo '</tr>';
}
echo '</table>';
?>

Related

Set a specific Time duration for page

I would like to specify the duration of the display of a form. Suppose there is a variable with the value x=(10), whenever I call this page, the timer should be based on the current time and the form should be displayed for 10 minutes and after this time the form should be sent automatically.
<?php
include 'db_conn.php';
if (isset($_GET['id'])) {
$var=$_GET['id'];
$query="SELECT * FROM addquiz WHERE quz_id='$var' ";
$db=mysqli_query($conn,$query);
$res=mysqli_fetch_array($db);
$noquestions=$res['noquestion'];
$quiz=$res['title'];
}?>
<div class="container">
<form method="POST" class="form-horizontal" >
<div style="margin-left: 30%;"><b>Your Quiz: <?php echo $quiz;?></b>
<input type="text" name="user_name" placeholder="Enter Your Name" style="height: 30px; width: 30%;"></div>
<div class="row">
<div class="col-md-12">
<div class="panel" style="margin:5%">
<?php
$count=1;
$que="SELECT * FROM addques WHERE quz_id='$var'";
$dbd=mysqli_query($conn,$que);
while ($cmd=mysqli_fetch_array($dbd)) {
$quest=$cmd['qusname'];
$ans_id=$cmd['ans_id'];
$opt1=$cmd['qpta'];
$opt2=$cmd['optb'];
$opt3=$cmd['optc'];
$opt4=$cmd['optd'];
$answ=$cmd['answer'];?>
<b>Question <?php echo $count++;?> :<br><?php echo $quest;?></b><br><br>
<fieldset>
<input type="hidden" name="ansid[]" value="<?php echo $ans_id; ?>">
<input type="checkbox" name="ans[]" value="1"><?php echo $opt1;?><br><br>
<input type="checkbox" name="ans[]" value="2"><?php echo $opt2;?><br><br>
<input type="checkbox" name="ans[]" value="3"><?php echo $opt3;?><br><br>
<input type="checkbox" name="ans[]" value="4"><?php echo $opt4?><br><br><br>
</fieldset>
<?php } ?>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
<div class="button" style="margin-left: 60%;"> View Result </div>
</div>
</div>
</div>
<?php
$i=0;
if (isset($_POST['submit'])) {
$name=$_POST['user_name'];
while ( $i<$noquestions ) {
$query="INSERT INTO `result`( `quz_id`, `ans_id`, `answer`,`user_name`) VALUES('";
$query.=$var . "', '";
$query.=$_POST['ansid'][$i] . "', '";
$query.=$_POST['ans'][$i] . "', '";
$query.=$name . "' )";
$db=mysqli_query($conn,$query);
$i++;
}
}
?>
It depends on what you are trying to achieve.
As you say "at each visit of the page" it could be done like this with javascript:
window.onload = function () {
window.setTimeout(function () {
document.form.submit();
}, 5000);
};
Further you could set the timeout from your php variable and like the comment says above, you could validate the taken time on the server side with php to make sure no one is cheating.

how to create a table in php with mysql?

I am trying to create a table for a leaderboard which displays users high scores for a game. I am using my sql to hold the data and php to get that data and put it into a table. when i go to this page on the site however, the page loads but all the php code shows up instead of the table. i dont know what im doing wrong, how do i get the php to display the table?
Sokoban Game
<body>
<div class="container">
<div class="header">
<h1>Sokoban</h1>
</div>
<div class="nav">
<div class="nav_wrapper">
<ul>
<li>Home</li><li>
Play</li><li>
Help</li><li>
Leaderboards
<ul>
<li>High Scores</li>
<li>Top Levels</li>
<li>Most completed</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="leftSideBar">
</div>
<div class="mainContent">
<h2>High Scores</h2>
<div class = "leaderboard">
<?php
// Get a connection for the database
require_once('../mysqli_connect.php');
// Create a query for the database
$query = "SELECT rankNo, username, highScores FROM Users INNER JOIN leaderboardHighScores";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
echo '<table>
<tr><td><b>Rank</b></td>
<td><b>Username</b></td>
<td><b>High Score</b></td></tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response)){
echo '<tr><td>' .
$row['rankNo'] . '</td><td>' .
$row['username'] . '</td><td>' .
$row['highScores'] . '</td><td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
</div>
</div>
<div class="rightSideBar">
<h3>Sign in</h3>
<input type="text" placeholder="Username" class="txtBox" /></br>
<input type="text" placeholder="Password" class="txtBox" /></br></br>
<input type="button" value="login" class="btn"/>
<h2>Sign up<h2>
<input type="button" value="Create account" class="btn"/>
</div>
</div>
</body>
</html>

Table Generator

Hi I have a question about generating rows and columns. would like to ask about how can I make it in one page only. This is what I have tried.
HTML:
<html>
<head>
<title>Table Generator</title>
<body>
<center><h1>Generate Your Table</h1></center>
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="get_table/execute_table.php" method="POST">
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
</body>
PHP:
<?php
$row = $_POST['title1'];
$column = $_POST['title2'];
echo "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
echo "<tr>";
for($td=1;$td<=$column;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Yes, it is fully running but I want it in 1 page only. Thanks.
Normally, if you want it on the same page, you just omit the action="" with its value.
Then of course, put the php process in the same page as the form:
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="" method="POST">
<!-- ^^ no more value, well you could just put the same filename -->
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
<?php
$out = ''; // initialize a string holder and when the submission is done, concatenate all the strings
if(isset($_POST['submit'])) { // catch submission button
$row = $_POST['title1'];
$column = $_POST['title2'];
$out .= "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
$out .= "<tr>";
for($td=1;$td<=$column;$td++){
$out .= "<td>row: ".$tr." column: ".$td."</td>";
}
$out .= "</tr>";
}
$out .= "</table>";
}
echo $out; // finally echo it
to achieve this by using only one page just leave the action attribute empty. and add your php block on top.and make sure to save it as .php and place your php code block on top of all html
so in the end it will look like this
<?php
$row = $_POST['title1'];
$column = $_POST['title2'];
echo "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
echo "<tr>";
for($td=1;$td<=$column;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
<html>
<head>
<title>Table Generator</title>
<body>
<center><h1>Generate Your Table</h1></center>
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="" method="POST">
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
</body>
You need to post to the same page, and check if the PhP Post array has data yet.
Replace the form action with:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
Note: although most (all?) browsers support self-posts with a blank action, this is not technically W3C compliant.
Then when the page is submitted it will reload the same page and populate the POST array. Somewhere on your page add a condition similar to:
if($_POST['title']){
//do whatever get_table/execute_table.php did
}else{
//echo the form here or, if you're allowed, use an include()
}
More info on self-posting:
How do I make a PHP form that submits to self?

PDO only fetches the 1st word of a string from the database

So when I try to fetch the names of categories from my database which, for example will be "Information & Technology", "Maths & Physics" "Off topic" using this code
<form method="POST" action="create_sub_cat.php">
<input type="text" name="sub_cat_name" value="" /><br>
<input type="text" name="sub_cat_desc" value""/><br>
<?
$get_cats = $dbh->prepare("SELECT * FROM forum_categories");
$get_cats->execute();
?>
<select name="cat_selection">
<?
while($cat = $get_cats->fetch(PDO::FETCH_OBJ)) {
echo '<option value='.$cat->cat_name.'>'.$cat->cat_name.'</option>';
}
?>
</select>
<input type="submit" value="Create Category!" name="create_sub_cat">
</form>
And store the category names as $selected_cat = $_POST['cat_selection'];
and echo it out it will echo out only the first word, so for example if I select "Information & Technology" it will only echo out "Information" or if I chose "Maths & Physics" it will only echo out "Maths" etc.
Here's the full code so that you kinda know what I'm trying to do.
<?php
if(isset($username) && $user_level == 3) {
?>
<div id="userbar">
<div id="announcement">Hello <?php echo '<a href=user.php?id='.$poster_id.'>'.$username.'<a>';?>
Log out</div>
</div>
<div id="menubar">
<ul id="menu">
<li ><a href="index.php" >Home</a></li>
<li ><a href="forum.php" >Forum</a></li>
<li ><a href="guides.php" >Guides</a></li>
<li >E-Sports</li>
</ul>
</div>
<form method="POST" action="create_sub_cat.php">
<input type="text" name="sub_cat_name" value="" /><br>
<input type="text" name="sub_cat_desc" value""/><br>
<?
$get_cats = $dbh->prepare("SELECT * FROM forum_categories");
$get_cats->execute();
?>
<select name="cat_selection">
<?
while($cat = $get_cats->fetch(PDO::FETCH_OBJ)) {
echo '<option value='.$cat->cat_name.'>'.$cat->cat_name.'</option>';
}
?>
</select>
<input type="submit" value="Create Category!" name="create_sub_cat">
</form>
<?php
}
else {
die("You don't have the access to this page.");
}
$sub_cat_name = $_POST['sub_cat_name'];
$sub_cat_desc = $_POST['sub_cat_desc'];
$selected_cat = $_POST['cat_selection'];
if(isset($_POST['create_sub_cat'])) {
try{
echo $selected_cat;
$cat_id = $dbh->prepare("SELECT * FROM forum_categories WHERE cat_name = :cat");
$cat_id->bindParam(':cat', $selected_cat, PDO::PARAM_STR);
$cat_id->execute();
$fetch_cat_id = $cat_id->fetch(PDO::FETCH_OBJ);
$fetched_cat_id = $fetch_cat_id->id;
$create_sub_cat = $dbh->prepare("INSERT INTO forum_sub_categories (cat_id, sub_cat_name, sub_cat_description) VALUES (:cat_id, :sub_cat_name, :sub_cat_desc)");
$create_sub_cat->bindParam(':cat_id', $fetched_cat_id, PDO::PARAM_INT);
$create_sub_cat->bindParam(':sub_cat_name', $sub_cat_name, PDO::PARAM_STR);
$create_sub_cat->bindParam(':sub_cat_desc', $sub_cat_desc, PDO::PARAM_STR);
$create_sub_cat->execute();
}catch(PDOException $e){
echo "An error occured";
error_log($e->getMessage());
}
}
?>
Just use quotation marks for value. Also I recommend the use of htmlspecialchars() (thanks to deceze in 1st comment)
echo '<option value="' . htmlspecialchars($cat->cat_name) . '">'.$cat->cat_name.'</option>';

javascript to reference input IDs in php loop and pass values back to same input ID

I have a form which is essentially an autocomplete input box. I can get this to work perfectly for a single text box. What I need to do is create unique input boxes by using a php for loop. This will use the counter $i to give each input box a unique name and id.
The problem is that the unique value of the input box needs to be passed to the javascript. this will then pass the inputted data to the external php page and return the mysql results.
As mentioned I have this working for a single input box but need assistance with passing the correct values to the javascript and returning it to correct input box.
existing code for working solution (first row works only, all other rows update first row input box)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
code for autocompleteperson.php is:
$query = $db->query("SELECT fullname FROM Persons WHERE fullname LIKE '$queryString%' LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.$result->fullname.'\');">'.$result->fullname.'</li>';
}
}
in order to get it to work for all rows, I include the counter $i in each of the file names as below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(inputString<? echo $i; ?>) {
if(inputString<? echo $i; ?>.length == 0) {
// Hide the suggestion box.
$('#suggestions<? echo $i; ?>').hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString<? echo $i; ?>+""}, function(data){
if(data.length >0) {
$('#suggestions<? echo $i; ?>').show();
$('#autoSuggestionsList<? echo $i; ?>').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString<? echo $i; ?>').val(thisValue);
setTimeout("$('#suggestions<? echo $i; ?>').hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions<? echo $i; ?>" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList<? echo $i; ?>">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
The autocomplete suggestion works (although always shown on first row) but when selecting the data always returns to row 1, even if input was on row 5. I have a feeling this has to do with the fill() but not sure? is it due the the autocomplete page code? or does the fill referencing ThisValue have something to do with it.
example of this page (as above) can be found here
Thanks for the assistance, much appreciated.
UPDATE - LOLO
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(i, inputString) {
if(inputValue.length == 0) {
// Hide the suggestion box.
$('#suggestions' + i).hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions' + i).show();
$('#autoSuggestionsList' + i).html(data);
}
});
}
} // lookup
function fill(i, thisValue) {
$('#inputString' + i).val(thisValue);
setTimeout("$('#suggestions' + i).hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString<?php echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions<? echo $i; ?>" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList<? echo $i; ?>">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
google chrome catched the following errors:
first line on input, second line on loosing focus
You cannot mix JS with PHP. PHP is a server-side language, you can render dynamic JS with that, but after it's rendered you cannot use PHP with JS. First of all you should change your JS functions, I suggest to add parameter like i which will contain input number:
<script type="text/javascript">
function lookup(i, inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions' + i).hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions' + i).show();
$('#autoSuggestionsList' + i).html(data);
}
});
}
} // lookup
function fill(i, thisValue) {
$('#inputString' + i).val(thisValue);
setTimeout("$('#suggestions" + i + "').hide();", 200);
}
</script>
Then change invokation of this functions and provide number:
<input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(<? echo $i; ?>, this.value);" onblur="fill(<? echo $i; ?>);" />
That should be enough.
The problem is with your code is you having same ID for all textbox and each DIV within for loop
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
It should be unique, like this edit.
<input type="text" size="30" value="" id="inputString<?php echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />

Categories