load/safe html form with mysql stored data - javascript

I build a simple html/js math-form where some calculations are beeing made with.
To simplify things I shortened the form to make it easier to understand:
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
document.getElementById('result1').innerHTML = (parseInt(value1) + parseInt(value2)) * parseInt(value3);
}
<select>
<option value="volvo">Simple Addition</option>
</select><button type="button">Load</button> <button type="button">Save</button> <button type="button">Cancel</button>
<br>
<br>
<br>
Title: <input id="Title" type="text"/>
<br>
<br>
<br>
<input id="value1" type="text" onchange="output();" />
<span> + </span>
<input id="value2" type="text" onchange="output();" />
<span> * </span>
<input id="value3" type="text" onchange="output();" />
<p>Result: <a id="result1"></p>
So, it's basically just a simple calculation. But I'm struggling to get the data stored with a mysql backend. The goal is:
a.) with a new calculation/form (non existing name in title-field), a new table should be created in mysql-db. Let's say we call the calculation "Simple Addition".
Simple-Addition should then be selectable via dropdown menu so others can load this calculation and even change/save/overwrite/correct it.
b.) So I want to be able to load, save and change any calculation to a mysql table and make it work that others can populate every stored calculation from a dropdown menu
c.) The maths should be named after the "Title" textfield
d.) autorefresh (kind of live collaboration like google sheets) all fields from database, let's say autorefresh every 5 seconds
I know this probably isn't a 5 min task, so I appreciate any of your help very very much. Thanks in advance!

Javasrcipt is a client-side language, it is won't communicate with MySQL server.
The possible solution is use AJAX call on client-side to save data by back-end PHP method.
this is only answer for the Save method. The load is similar like this, but you should use 'GET' instead of 'POST'.
AJAX call:
<button onclick="Save();">Save</button>
<script>
function Save()
{
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
var value4 = document.getElementById('title').value;
var inputsAndResult= [value1, value2, value3, title ];
$.ajax({
url : 'YOUR_URL',
method : 'POST',
data :{
arrayData:inputsAndResult
},
success : function(response)
{
alert("succes");
},
error : function(e)
{
alert("error")
}
});
}
</script>
on the backend side:
<?php
$server = "localhost";
$db = "myDB";
$conn = mysqli_connect($server, $db);
$sql = "INSERT INTO MyGuests ( number1, number2, result, name ])
VALUES ($_POST[dataArray[0]], $_POST[dataArray[1]], $_POST[dataArray[2]], $_POST[dataArray[3]])";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
These pages really good to get the basic about all of these thing like AJAX,PHP, database posting.
PHP:
https://code.tutsplus.com/courses/php-fundamentals
https://www.w3schools.com/php/default.asp
AJAX:
https://www.w3schools.com/xml/ajax_intro.asp
AJAX posting into MySQL:
https://www.w3schools.com/php/php_ajax_database.asp

Related

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

not working form and form variable validation?

my form
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon" onclick="searchToggle(this, event);"><i class="fas fa-search"></i></button>
</div>
api.php
case 'metafind': {
$string = $_GET['string'];
$list = mysqli_query($connect, "SELECT * FROM `sub_meta` WHERE `meta_key` = 'Название'&& `meta_value` ");
while ($item = mysqli_fetch_assoc($list)) {
if ($item['meta_value'] == $string) {
$id = $item['post_id'];
$arrr[] = array('post_id' => $item['post_id'], 'coords' => $find['meta_value']);
}
}
echo json_encode($arrr);
} break;
when you click on the form gives an error in the console:
(index):121 Uncaught ReferenceError: searchToggle is not defined
at HTMLButtonElement.onclick ((index):121)
it is necessary that when a word is entered into the form it was
searched for a name in the column meta_value by meta_key and then
displayed please help I'm new to php
You should try something like my below example :
1) I created textbox where i will write data then it will search in array and get the value from there where i have made array for example purpose and display the data in #div1
<div class="input-holder">
<input type="text" class="search-input" id="string" placeholder="Искать" />
<button class="search-icon"><i class="fas fa-search"></i>Go</button>
<div id="div1"> </div>
</div>
2) When button click we have to do ajax call then we will get data from there and get that data in response and we will show that response where we want to display
<script>
$(document).ready(function(){
$("button").click(function(){
var stringval = $("#string").val();
$.ajax({data: {val : stringval} , url: "democode.php", type: 'post', success:
function(result){
var data = JSON.parse(result);
console.log(data);
$("#div1").html(data);
}});
});
});
</script>
3) Ajax call on democode.php so in that file we will get data there(you can get data from database if you want) and we will return the data
==democode.php==
<?php
$test['data'] = array("Aleaxa"=>"I'm Beutiful","john"=>"I'm Evil","mishel"=>"baby, I'm Bad Boy!","mohini"=>"I'm MAstana");
if (array_key_exists( $_POST['val'], $test['data'])) {
$key = $_POST['val'];
echo json_encode($test['data'][$key]);
}
?>
So above example work like if i will search Aleaxa and click go button then it will give value of Aleaxa from array and output will be I'm Beutiful
Please checked my demo you will get idea how to do the code with your requirements

Output Data From MYSQL Table Into HTML Form Depending On User Choice

I have a MYSQL table (roomcost) that holds the costs of hiring rooms.
costID Room Cost
1 room1 15
2 room2 30
3 room3 50
rsRoomCost SQL is: SELECT * FROM roomcost
The HTML form has checkboxes that allow the hirer to make the choice of Room 1, Room 2 or Room 3. The hirer can hire one, any two or all three rooms.
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</div>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</div>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</div>
The form also has an input box (that will be hidden, once I get it working) for each room that will be filled with the appropriate cost from the table. When the form is submitted, the hirers record would hold the choice of room(s) and cost paid by that hirer at the time of hiring.
The JS script that checks if a particular checkbox is selected and would output the cost to the relevant input box.
function Check() {
if (document.forms["bookform"].room1.checked) {
document.forms["bookform"].thisRoom1.value = "<?php echo($row_rsRoomCost['room1']; ?>";
} else if (document.forms["bookform"].room2.checked) {
document.forms["bookform"].thisRoom2.value = "<?php echo($row_rsRoomCost['room2']; ?>";
} else if (document.forms["bookform"].room3.checked) {
document.forms["bookform"].thisRoom3.value = "<?php echo($row_rsRoomCost['room3']; ?>";
}
}
The input boxes for the output are:
Room 1: <input type="text" name="thisRoom1" value="">
Room 2: <input type="text" name="thisRoom2" value="">
Room 3: <input type="text" name="thisRoom3" value="">
As you see, I'm trying to use php to fill in the relevant value from the database table. However, this, of course, only shows the cost from the first record in the costs table regardless of which room is checked.
How do I get the cost of the chosen room from the table into the correct input box on the form?
I've tried <?php echo($row_rsRoomCost['room1']) where ($row_rsRoomCost['costID']) = '1'; ?> but this doesn't work. I thought about 'case' statements but don't know how that would work. The only way I can think of is a seperate SQL statement for each room. eg: SELECT * FROM roomcost WHERE costID = 1
How do I get the cost of the selected room from the table into the correct input box on the form?
Going through your code I find that that would be the long way round of solving it .
The first step to solving it would be to put your data into a reusable front End source like JSON (it easier to work with ).
Example: (Results are in the console log F12)
<?php
$servername = "localhost";
$username = "root";
$password = "jono23";
$dbname = "helpothers";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `roomcost`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// echo "id: " . $row["costID"]. " - Name: " . $row["room"]. " " .$row["cost"]. "<br>";
// data you want to send to json
$data[] = array(
'id' => $row['costID'],
'room' => $row['room'],
'cost' => $row['cost']
);
//}
}
} else {
echo "0 results";
}
$conn->close();
$json_data = json_encode($data);
//print_r($json_data);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id='bookform' >
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</input>
<input type="text" name="room1value" readonly><br>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</input>
<input type="text" name="room2value" readonly><br>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</input>
<input type="text" name="room3value" readonly><br>
</form >
<script type="text/javascript">
var Rooms = JSON.parse('<?php print_r($json_data) ; ?>');
console.log(Rooms);
function Check() {
//room1
if (document.forms["bookform"].room1.checked)
{
document.forms["bookform"].room1value.value = Rooms[0].cost;
console.log(Rooms[0].cost);
}else{
document.forms["bookform"].room1value.value ='';
}
//room2
if (document.forms["bookform"].room2.checked)
{
document.forms["bookform"].room2value.value = Rooms[1].cost;
console.log(Rooms[1].cost);
}else{
document.forms["bookform"].room2value.value ='';
}
//room3
if (document.forms["bookform"].room3.checked)
{
document.forms["bookform"].room3value.value = Rooms[2].cost;
console.log(Rooms[2].cost);
}else{
document.forms["bookform"].room3value.value ='';
}
}
</script>
</body>
</html>
By encoding the SQL query results into a json array first you able to
close the database connection so not to use up unnecessary resources
on multiple requests
Then By calling that PHP JSON Object into JavaScript you can more easily apply it to your html and JavaScript Needs
Converting PHP Data To JSON and parse with JavaScript Help us work with things like rest api's
This is the main reason why JSON implementation can be found in many languages as its an easy way to share data across different coding languages
Another suggestion that I would make for the handling of the data is not to store the values in a checkboxes . Create another text input for that purpose and store them there . e.g
<input type='text' id='gethandle1'>
<script>
let box1 = document.getElementById('gethandle1');
box1.value = Rooms[0].cost;
</script>
I hope this helps you .

post image, selected values to php via Javascript

Hello as part of my website project I am writing an item input form, the website itself is very simple, the user will:
Write item name
Select some values
Write item description in textarea
Upload item image
the page will collect this info using JS and then sent to PHP page where it will be checked and then inserted into database. I am not sure what is wrong with the code --php page gives no errors-- as it is not responding after submission, tried resolving by process of elimination, deleting the image part in JS seems to make the button respond though no output is given.
<!DOCTYPE HTML>
<html>
<header>
<title> Results </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</header>
<body>
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>Add item form.. </legend>
<p> fill out the below details </p>
<p> Item name will be publicly viewed by users: <input type="text" id="itemID" name="itemName" placeholder="Enter item name.." /> </p>
location:
<select id="locSelect"> //4 options for every select
<option id="mountainID" value="mountain"> Mountain </option>
</select>
Category:
<select id="catSelect">
<option id="appliancesID" value="appliances"> Appliances </option>
</select>
Price range:
<select id="rangeSelect">
<option id="range1ID" value="range1"> 0-$50 </option>
</select>
<p> <input type="textarea" id="descriptionID" name="descriptionName" style="height:185px;width:400px;" placeholder="Please enter any item relevant info in this area..." /> </p>
<p> Upload Image: <input type="file" id="itemImageID" name="itemImage" /> </p>
<p> <input type="button" id="addID" name="add" value="Add item" onClick="runAdd();" /> </p>
</fieldset>
</form>
<div id="addResult"></div>
<script type="text/javascript">
function runAdd()
{
var item = $("#itemID").val();
var location = document.getElementById("locSelect"); //id of select
var selectedLoc = location.options[location.selectedIndex].text;
var category = document.getElementById("catSelect");
var selectedCat = category.options[category.selectedIndex].text;
var range = document.getElementById("rangeSelect");
var selectedRange = range.options[range.selectedIndex].text;
var textArea = document.getElementById("descriptionID").value;
var itemImg = document.getElementById("itemImageID");
$.post("itemDatabase.php", {
itemDB: item,
locationDB: selectedLoc,
categoryDB: selectedCat,
rangeDB: selectedRange,
textareaDB: textArea,
itemImgDB: itemImg },
function(data)
{
if(data == "int echoed by php page"){
$("#addResult").html("item/text is blank..");
//php will echo back to addResult <div> if input is not set
}
}
);
}
</script>
</body>
</html>
I believe I am sending the textarea, select and image parts wrongly, as php echos nothing for them when they are empty. I looked up codes online though they were separate from my case usually involving AJAX or PHP exclusively.
<?php
session_start(); //for userID, different page stores it
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project_database");
if (isset($_POST['add'])){
if(empty(trim($_POST['itemDB']))) { // if(!($_POST['itemDB'])) not working
echo "0"; }
else { $item = mysql_real_escape_string($_POST['itemDB']); }
if(isset($_POST['locationDB'])){
$location = $_POST['locationDB'];
} else {
echo "1"; }
if(isset($_POST['categoryDB'])){
$category = $_POST['categoryDB'];
} else {
echo "2"; }
if(isset($_POST['rangeDB'])){
$range = $_POST['rangeDB'];
} else {
echo "3"; }
if(empty(trim($_POST['textareaDB']))) {
echo "4"; }
else { $description = mysql_real_escape_string($_POST['textareaDB']); }
if(getimagesize($_FILES['itemImgDB']['tmp_name']) == FALSE)
{
echo "5";
}
else
{
$image = addslashes($_FILES['itemImgDB']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
}
$query = "INSERT INTO item (item_name, item_description, item_price_range, item_img, item_location, user_id, category_id) VALUES ('".$item."', '".$description."', '".$range."', '".$image."', '".$location."', '".$_SESSION["userID"]."', '".$category."')";
$itemAdded = mysql_query($query);
if($itemAdded) {
echo " Item " .$item. " has been added successfully "; }
else { echo " something went wrong "; }
}
?>
category_Id and user_id are foreign keys,
Image is stored as BLOB in database (checked code working on different page)
I understand some functions are deprecated, but this is how I was instructed to complete my task, I am using notepad.
I have posted most of the code to ensure I understand what is wrong or how I can improve it in the future, I appreciate any pointers or tips just to get me on the right path at least so I can fix this.
Thank you again for any help in advance.
To answer your question about uploading images via AJAX, this was not possible before but it is now possible via FormData objects (but it is a relatively new feature and is not compatible with older browsers, if that matters to you).
You might either want to upload the image separately (old fashioned), or I suggest you look into using FormData.
This link below should be helpful (I hope):
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Hope this helps :)

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

Categories

Resources