Rerun PHP Script inside HTML file without reloading page - javascript

I want to rerun a PHP File which was loaded in a div in my HTML code. On my main page, I have a form and a table. The form adds rows to the MySQL table, and the table on the page outputs that MySQL table. I want the table on the HTML page to update when the new row is added via the form, without refreshing the page. I tried putting the load command in the success part of the ajax function for my form but that didn't work. I looked at many other answers and none worked for me.
This is my code
redeem.php
<h1>Rewards</h1>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required>
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required>
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
tables.php
<?php
$host = "";
$user = "";
$pass = "";
$db_name = "";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT RewardName, PointsRequired FROM rewards");
$all_reward = array(); //declare an array for saving property
while ($reward = mysqli_fetch_field($result)) {
// echo '<th scope="col">' . $reward->name . '</th>'; //get field name for header
array_push($all_reward, $reward->name); //save those to array
}
// echo ' </tr>
// </thead>'; //end tr tag
echo '<table class="table">
<thead>
<tr>
<th scope="col">Reward</th>
<th scope="col">Points Required</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>';
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tbody>
<tr>";
foreach ($all_reward as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '<td><i class="fas fa-edit"></i></td>';
echo '<td><i class="fas fa-trash"></i></td>';
echo ' </tr>
</tbody>';
}
echo "</table>";
?>
redeem-form.js
$(document).ready(function() {
$("#add-reward-form").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "add_rewards.php",
method: "POST",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$("#add-reward-form")[0].reset();
$("#sql-table").load(" #sql-table > *");
}
});
$("#sql-table").load(" #sql-table > *");
});
});
The form works perfectly fine with ajax, and submits to the database without refreshing. But I would like to update the table on my page as well without reloading.
$("#sql-table").load(" #sql-table > *");
This is what I tried. I placed it inside the success function and the submit function but both did not work.

You are mis-using $.load(). It's a shorthand for $.ajax(). The first argument must be a URL. Optional arguments are data and options.
You are passing it a selector, so the request fails. As-is, $("#sql-table").load(" #sql-table > *"); is attempting an AJAX request to the URL /%20#sql-table%20%3E%20*. (!)
Simply change the selector for the PHP file you want to execute:
$("#sql-table").load("tables.php");

How about forcing redeem.php to re-evaluate the PHP div every time a change happens to the inputs?
<h1>Rewards</h1>
<script>
function redrawSQLTable(){
document.getElementById('sql-table').innerHTML = "<?php include 'tables.php'; ?>"
}
</script>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required onchange="redrawSQLTable()">
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required onchange="redrawSQLTable()">
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>

Related

passing value to hidden input value before submit

I am trying to run a form that stores an Id in a hidden input tag so that I can retrieve it in the next page using php. For some reason I can't retrieve the value using the php file. Echoing orderId.value and order number are working fine.
main_page.php
<script>
function EditValues(orderNumber) {
var orderId = document.getElementById("orderId");
orderId.value = orderNumber;
document.forms["form1"].submit();
}
</script>
<body>
<form action="edit-form.php" id="form1">
<div class="container">
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId"/>
<?php
require("config.php");
$con = new mysqli(DB_Host, DB_User, DB_Password, DB_Name);
if ($con->connect_error) {
die("Connection failed");
}
echo '<table id="tblOrders" name ="OrderTable" style="width: 100%">
<tr>
<th>Sno</th>
<th>Order Number</th>
</tr>';
$displayTableDataQuery = "SELECT id, orderNumber, customerName, deliveryDate FROM orderTable";
if ($tableData = $con-> query($displayTableDataQuery)) {
while($row = $tableData-> fetch_assoc()) {
$id = $row['id'];
$orderNumber = $row["orderNumber"];
echo '<tr >
<td>'.$id.'</td>
<td id = "orderNumber">'.$orderNumber.'</td>
<td><input type = "button" id ="editButton'.$id.'" value = "Edit" onclick = "EditValues('.$orderNumber.');"/> </td>
<td><input type = "button" id = "printInvoice'.$id.'" value="Print" onclick = "PrintInvoice('.$orderNumber.');" /> </td>
</tr>';
}
} else {
echo $con->error;
}
$tableData->free();
?>
</div>
</form>
</body>
In edit-form.php
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
There is nothing echoed for $xyzabc
I would prefer if there was some way to do this without jQuery as I'm kind of new to this and haven't really gotten a hang of how everything works together as of now.
You can store value directly to the hidden input field.
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId" value="<?=$variable_name;?> />
So that when you submit the form
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
will fetch the data.
Or you can pass the hidden value in url. For example
<a href="localhost:8000/edit-form.php?orderId="<?=$variable_name;?>
Then in you form-edit.php
<?php
$xyzabc = $_GET['orderId'];
echo $xyzabc;
?>

How to display new records on screen without refreshing the page?

I have to display the all the records on the screen which are inserted into the database without refreshing the page. I have 3 columns called as Firstname, Lastname, Email and after clicking on the submit button data are inserting in the database using ajax Which is working.
Now I am fetching the records on the same screen without refresh the page but it is not working when I am refreshing the page then it is displaying the last record which is inserted.
Please check below link. You will get an idea what I am asking. Inserted data and display data at the same time.
http://prntscr.com/g953bs
Index.php
<?php
ob_start();
session_start();
include('../../db/connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" id="register" autocomplete="off">
<input type="text" name="fname" id="fname" placeholder="Firstname">
<input type="text" name="lname" id="lname" placeholder="Lastname">
<input type="email" name="email" id="email" placeholder="Email">
<input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;">
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['fname']."</td>
<td>".$row['lname']."</td>
<td>".$row['email']."</td>
</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#register').submit(function(e){
e.preventDefault(); // Prevent Default Submission
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
// $("#table-container").html(data);
$("#register")[0].reset();
},
});
});
</script>
</body>
</html>
Process.php
$firstname=$_POST['fname'];
$lastname=$_POST['lname'];
$email=$_POST['email'];
$sql = "INSERT INTO test1 (fname, lname, email) VALUES ('$firstname', '$lastname', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
$('#IdTable tr:last').after('<tr><td>id<td>fname<td>lname<td>email</tr>');
Define id to the table
<table border="1" style="margin-top: 25px;" id="myTable">
Changes in ajax call
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
$('#myTable tr:last').after('<tr><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
$("#register")[0].reset();
},
});
Note: Also you should handle the case if eror while inserting in your code as currently you are only taking positive case.
I hope this will help
First of all I'd like to suggest taking a look at binding parameters with mysqli to make your query saver.
Then in order to add the date without refreshing you could return the data on successful insert. Then append this data to the table.
Example Process.php
if (mysqli_query($conn, $sql)) {
echo "<tr>
<td>".mysqli_insert_id($conn)."</td>
<td>".$firstname."</td>
<td>".$lastname."</td>
<td>".$email."</td>
</tr>";
} else {
As you have only one table then use below code.
$('table tr:last').after('<tr>...</tr><tr>...</tr>');
If you have any class or id then you can modify below syntax as $('selector tr:last')
Use it in success of ajax call

ajax delete post asynchronously - php

I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});

How can I update a specific record in a sql database based on a selection made in a dropdown select box?

Ok, I have spent days on this, and I am out of my depth. I admit I am completely new to sql, jquery, and ajax. I apologize in advance for this.
I am trying to build an application where an admin can see a users performance over time, averaging the last 2 weeks of input scores. Using a dropdown box a member should be selected from the DB (this part seems to work), then a form below can be filled out and an "update" button pressed to update the record in the DB (this is completely broken).
The select box is populated from the DB with ajax, and I can return values from the selection with an onchange function, but when I try to then update the database with my form, nothing is updated.
The insert button and associated code work properly, and information is stored correctly in the DB. (I will break the data off into more accurate tables when I have the code correct as I did not want to deal with joins and multiple tables while struggling.)
When selecting a name from the select menu $_POST['memberID'] shows the correct number.
Once information is entered into the form and "update" is pressed, $_POST['memberID'] is blank and the DB is not updated.
Controller.php:
<?php require 'php/dbconnect.php';
$records = array();
if(!empty($_POST)) {
switch (true) {
case isset($_POST['insert']):
if(isset($_POST['name'], $_POST['designation'], $_POST['rank'], $_POST['currentScore'])) {
// The following trim functions followed by !empty ensures that a series of spaces is not accepted from users as input.
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$rank = trim($_POST['rank']);
$currentScore = trim($_POST['currentScore']);
if(!empty($name) && !empty($designation) && !empty($rank) && !empty($currentScore)) {
$insert = $conn->prepare("INSERT INTO members (name, designation, rank, currentScore) VALUES (?,?,?,?)");
$insert->bind_param('ssii' , $name, $designation, $rank, $currentScore);
if($insert->execute()) {
$insert->free(); //Remove Query Data from memory since it is no longer needed.
header('location: index.php');
die();
}
}
}
break;
case isset($_POST['update']):
$name = trim($_POST['name']);
if(!empty($name)) {
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
$update->bind_param('s', $name);
if($update->execute()) {
header('location: index.php');
die();
}
}
break;
// case isset($_POST['delete']):
// // Delete statement goes here
// break;
// else
}
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row; //Appending value to array
}
$results->free();
}
}
?>
Index.php:
<?php include 'header.php' ?>
<?php if(!count($records)) {
echo 'No Records' ;
} else {
?>
<form id="memberSelect" method="post">
<select name="memberID" id="members" onchange="change()">
<!-- Populated with function members in footer.php -->
</select>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Rank</th>
<th>Previous Score</th>
<th>Current Score</th>
<th>Average Score</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r) {
?>
<tr>
<td><?php echo escape($r->name); ?></td>
<td><?php echo escape($r->designation); ?></td>
<td><?php echo escape($r->rank); ?></td>
<td><?php echo escape($r->previousScore); ?></td>
<td><?php echo escape($r->currentScore); ?></td>
<td><?php echo escape($r->avgScore); ?></td>
<!-- Remember when putting data in that current score needs to be moved to previous score's
position and the NEW score will take the place of current score(which will be the old score until updated) -->
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<hr>
<form action="" method="post">
<div class="field">
<label for="name">Member name</label>
<input type="text" name="name" id="name" autocomplete="off">
</div>
<div class="field">
<label for="designation">Designation</label>
<input type="text" name="designation" id="designation" autocomplete="off">
</div>
<div class="field">
<label for="rank">Rank</label>
<input type="text" name="rank" id="charLevel" autocomplete="off">
</div>
<div class="field">
<label for="currentScore">Current Score</label>
<input type="text" name="currentScore" id="currentScore" autocomplete="off">
</div>
<div id="submit">
<!-- Add a comment section to be input into DB -->
<input type="submit" name="insert" value="Insert">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<!-- <input type="hidden" name="id" value="<?php //echo $?>"> -->
</div>
</form>
<?php include 'footer.php' ?>
Footer.php:
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script>
//How do you explain something you barely understand? The following function uses JQUERY
//json, and ajax to fill a select dropdown with items populated from a linked database.
//See the jsonData.php for the json data being referenced here, it is imperitive to the operation of
//this function that json data be available.
function members(){
$('#members').empty();//Removes all content of the associated ID 'members' to ensure a clean default value
$('#members').append("<option>Loading</option>");//fill them with a default message
$.ajax({
type:"POST",
url:"php/jsonData.php",//the location of the json data, for this it is required to be in its own file
contentType:"application/json; charset=utf-8",
dataType: "json",
success: function(records){ //only fires if the json data is found
$('#members').empty();//If everything is ok, removes previous default value
$('#members').append("<option value='0'>--Select Member--</option>");
$.each(records,function(i,memberID){//Uses a foreach loop to fire a function for every memberID, assigning the value to i
$('#members').append('<option value="'+ records[i].memberID +'">'+ records[i].name +'</option>');
//^ The workhorse. Grabs the select value by the ID, appends the option value by looking within the records array
//(which is defined and assigned values in the jsonData.php file) and assigns the member id as the value and the 'name'
//as the option. This populates the dropdown with the names and gives them the value 'memberID' from the database.
});
},
complete: function(){
}
});
}
$(document).ready(function(){
members();
});
</script>
<script>
function change(){
$('#memberSelect').submit();//Submits the page to the server when called
}
</script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
I think the problem is in this line of the Update Block:
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
I am assuming the primary key of your member table is: member_id
Then this code will be:
$update = $conn->prepare("UPDATE members SET name = ? WHERE member_id = ?");
$update->bind_param('si', $name, $memberID);
Try this. Hope it helps.

How to execute sql delete query on button click using javascript function in PHP

I have three files, index.html, database.php, and function.js. In my database.php, I have created a form with a delete button to execute the delete sql query on click. My main purpose is to display a table with records displayed and a delete button on each so that whenever I click the delete button, it executes the SQL query and removes that particular row from the database.
It works fine before I added in ajax into the javascript. Now when delete button is clicked, the whole page just refreshes.
How do I execute the delete query on the delete button click using a javascript function that I want to call in my php file without creating/using new files?
I am using vi editor to code so I do not have any means of debugging except IE's developer tools. My javascript file doesn't seem to be working because in the HTML file the form returns a null at
onsubmit="return checkFields()";
as stated from the error I received, but it's probably just because there are errors in my javascript file.
P.S. I am new to PHP, javascript, and ajax so do pardon me if I make any careless or obvious mistakes. I also do not know any jQuery or JSON. Any form of help in the simplest explanation would be greatly appreciated.
Here is the index.html file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
Here is the database.php file:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwe');
DEFINE ('DB_PASSWORD', 'inqwe123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'hqwdqq');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){//java script function somewhere
echo "<script>";
echo "deleteRow()";
echo "</script>";
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id']; ?>"/>
<input type="button" name="delete" value="Delete" onclick="return deleteRow(<?php echo $row['user_id']; ?>);"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>
And here is the function.js file:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
return false;
}
}
else{
return false;
}
}
function deleteRow(id){
if(confirm("Are you sure you want to delete this contact?")){
//$id = $_POST['user_id'];
$query_string = "delete from $table_info where user_id='id';
$result = mysql_query($result) or die ('Could not execute.'. mysql_error());
return false;
}
}
It looks like you're missing a closing double-quote at the end of this line:
$query_string = "delete from $table_info where user_id='id';
It should read:
$query_string = "delete from $table_info where user_id='id'";
There may be other errors as well. You should learn to use your browser's built-in script debugging features (and/or download one if your browser doesn't have one). For example, try Firebug and the Web Developer Toolbar for Firefox.

Categories

Resources