Editing table data using php, PDO, and Ajax - php

I have a data table that displays the counter table in the database.
It has create and edit buttons, each linked to a pop-up modal. The create button works fine, but I'm having an issue with the edit button.
When I click the edit button in a row, it's supposed to retrieve the data from the database table and display them in the text fields of the edit modal.
The data gets retrieved without any issues. But, the only thing that gets displayed in the edit modal is the id. The rest of the data gets displayed in the create modal.
I tried to find the error but I couldn't figure it out yet.
This is the counter table
CREATE TABLE IF NOT EXISTS `counter` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`created_at` date DEFAULT NULL,
`updated_at` date DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Here's how the code goes.
create modal
<div id="addModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Counter</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="" method="post" id="form-data" novalidate>
<div class=" form-group">
<label>Counter Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class=" form-group">
<label>Description</label>
<textarea name="desc" id="desc" class="form-control" rows="4" cols="50" required></textarea>
</div>
<div class="form-group">
<label>Status</label><br>
<input type="radio" id="status" name="status" value="1" checked required>
<label for="avtive">Active</label><br>
<input type="radio" id="status" name="status" value="0">
<label for="avtive">Inactive</label><br>
</div>
<div class="form-group">
<input type="reset" class="btn btn-secondary" />
<input type="submit" id="insert" name="insert" value="Add Counter" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
edit modal
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Counter</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="" method="post" id="edit-form-data" novalidate>
<input type="text" name="id" id="id">
<div class=" form-group">
<label>Counter Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class=" form-group">
<label>Description</label>
<textarea name="desc" id="desc" class="form-control" rows="4" cols="50" required></textarea>
</div>
<div class="form-group">
<label>Status</label><br>
<input type="radio" id="status" name="status" value="1" checked required>
<label for="avtive">Active</label><br>
<input type="radio" id="status" name="status" value="0">
<label for="avtive">Inactive</label><br>
</div>
<div class="form-group">
<input type="reset" class="btn btn-secondary" />
<input type="submit" id="update" name="update" value="Edit Counter" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
script
<script>
$(document).ready(function() {
//edit ajax request
$("body").on("click", ".editBtn", function(e) {
// console.log("working");
e.preventDefault();
edit_id = $(this).attr('id');
$.ajax({
url: "../../php/admin-action.php",
type: "POST",
data: {
edit_id: edit_id
},
success: function(response) {
data = JSON.parse(response);
// console.log(data);
$("#id").val(data.id);
$("#name").val(data.name);
$("#desc").val(data.description);
$("#status").val(data.status);
},
error: function(response) {
toastr.error('Error detected while adding, Please try again later!');
}
})
})
// update ajax request
$("#update").click(function(e) {
if ($("#edit-form-data")[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "../../php/admin-action.php",
type: "POST",
data: $("#edit-form-data").serialize() + "&action=update",
success: function(response) {
toastr.success('Counter edited successfully!');
setInterval(2000);
$("#editModal").modal('hide');
$("#edit-form-data")[0].reset();
showAllCounters();
},
error: function(response) {
toastr.error('Error detected while editing, Please try again later!');
}
})
}
})
});
</script>
admin-action.php
// handle view counter list
if (isset($_POST['action']) && $_POST['action'] == 'view') {
$output = '';
$data = $db->read_counter();
if ($db->totalRowCount_counter() > 0) {
$output .= '<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Counter</th>
<th>Description</th>
<th>Created Date</th>
<th>Updated Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($data as $row) {
$output .= ' <tr>
<td>' . $row['id'] . '</td>
<td>' . $row['name'] . '</td>
<td>' . $row['description'] . '</td>
<td>' . $row['created_at'] . '</td>
<td>' . $row['updated_at'] . '</td>
<td>' . $row['status'] . '</td>
<td class="project-actions text-right">
<a class="btn btn-primary btn-sm viewBtn" id="' . $row['id'] . '">
<i class="fas fa-folder">
</i>
View
</a>
<a class="btn btn-info btn-sm editBtn" data-toggle="modal" data-target="#editModal" id="' . $row['id'] . '">
<i class="fas fa-pencil-alt">
</i>
Edit
</a>
<a class="btn btn-danger btn-sm dltBtn" id="' . $row['id'] . '">
<i class="fas fa-trash">
</i>
Delete
</a>
</td></tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h3 class="text-center text-secondary mt-5">:(No counters present in the database!)</h3>';
}
// print_r($data);
}
if (isset($_POST['action']) && $_POST['action'] == 'insert') {
$name = $_POST['name'];
$desc = $_POST['desc'];
$status = $_POST['status'];
$db->insert_counter($name, $desc, $status);
}
if (isset($_POST['edit_id'])) {
$id = $_POST['edit_id'];
$row = $db->getCounterByID($id);
echo json_encode($row);
}
if (isset($_POST['action']) && $_POST['action'] == 'update') {
$id = $_POST['id'];
$name = $_POST['name'];
$desc = $_POST['desc'];
$status = $_POST['status'];
$db->update_counter($id, $name, $desc, $status);
}
admin-db.php
public function getCounterById($id)
{
$sql = "SELECT * FROM counter WHERE id = $id";
$stmt = $this->conn->prepare($sql);
$stmt->execute(['id' => $id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function update_counter($id, $name, $desc, $status)
{
$sql = "UPDATE counter SET name=:name, desc=:desc,status=:status WHERE id = :id ";
$stmt = $this->conn->prepare($sql);
$stmt->execute(['name' => $name, 'desc' => $desc, 'status' => $status, 'id' => $id]);
return true;
}
I'm posting all of the code because I'm not exactly sure where the problem is. Apologies for making it so long.

FIRST OF ALL
You should not use the same value for HTML id attribute. You used in both create and edit form the same ids for the input fields. The value of the id attribute has to be unique on the entire HTML page, even if some parts are hidden.
CURRENT BEHAVIOR
Your create form does not have an input field with attribute id='id', that is why the corresponding input field is filled after the ajax request.But the other 4 input fields exist in both forms. Because the create form is placed before the update form in your HTML content, the input fields of create form are filled.
SOLUTION
Please change your success function of your .editBtn click handler like this:
success: function(response) {
data = JSON.parse(response);
// console.log(data);
let $form = $('#edit-form-data');
let radioId = data.status === "1" ? "#editStatusActive" : "#editStatusInactive";
$form.find("input[id='id']").val(data.id);
$form.find("input[name='name']").val(data.name);
$form.find("[name='desc']").val(data.description);
$form.find(radioId).click();
},
},
Then update the form group for status in your update form like this:
<div class="form-group">
<label>Status</label><br>
<input type="radio" name="status" id="editStatusActive" value="1" checked required>
<label for="editStatusActive">Active</label><br>
<input type="radio" name="status" id="editStatusInactive" value="0">
<label for="editStatusInactive">Inactive</label><br>
</div>

Related

Get data from controller and show it via AJAX

I want to get data from a controller and display it in a html pop-up when a button is clicked.
At this point the POPUP is showing when the button is clicked but the data isn't loaded
At this point I need that onclick the values get loaded and show them in the popup.
index.blade.php
<button data-toggle="modal" data-target="#edit" id ="uid" name="uid" value="<?php echo $user->id ?>">
</button>
<div class="modal fade" id="edit" tabindex="-1" role="">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="card card-signup card-plain">
<div class="modal-header">
<div class="card-header card-header-primary text-center">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="card-title">Editar</h4>
</div>
</div>
<div class="modal-body">
<form class="form" method="POST" action = "{{ route('/alteruser') }}" name = 'user'>
#csrf
<div class="card-body">
<div class="form-group bmd-form-group">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="material-icons"></i>
</div>
</div>
<input name = 'name' type="text" class="form-control" placeholder="<?php echo $seluser->id ?? ''?>" id='id' disabled>
<input name = 'name' type="text" class="form-control" "<?php echo $seluser->name ?? ''?>" id='name'>
<input type="text" class="form-control" placeholder="<?php echo $seluser->email ?? ''?>" id = 'email'>
<input type="password" placeholder="<?php echo $seluser->password ?? ''?>" class="form-control" id = 'password'>
<input type="text" placeholder="<?php echo $seluser->nif ?? ''?>" class="form-control" id = 'nif'>
<input type="text" placeholder="<?php echo $seluser->contacto ?? ''?>" class="form-control" id = 'contact'>
<input type="text" placeholder="Grupo" class="form-control" id = 'grupo'>
</div>
</div>
<button type="submit" class="btn btn-primary btn-link btn-wd btn-lg" name = 'uid'>Confirmar</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
UserController#GetUser:
public function getUser() {
$id = $_POST['uid'];
$seluser = DB::table('users') -> where('id', $id) -> first();
$view = view('/users/index',compact('seluser'))->render();
return response(['status'=> 1, 'data' => $view]);
}
Ajax code in index.blade.php:
$(document).ready(function(){
$("#uid").click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: baseUrl+"/getUser",
data:{uid: $("#uid").val()},
dataType: 'json',
success: function(data) {
$('#edit').html(data.html);
}
});
});
});
I'm new at AJAX so i assume the error is in it
you should return response instead of view in controller like below
public function getUser()
{
$_SESSION['getUser'] = 1;
echo "AAA";
$id = $_POST['uid'];
$seluser = DB::table('users')
-> where('id', $id)
-> first();
$view = view('/users/index',compact('seluser'))->render();
return response(['html' => $view]);
}
and get response like below
$.ajax({
type: 'POST',
url: baseUrl+"/getUser",
data:{uid:uid},
dataType: 'json',
success: function(data) {
$('#edit').html(data.html);
}
});

select onchange update php id and then query mysql

I have a select with a information modal/button that I want to dinamically connect when select is changed
My code like this
<select name="name_select" id="my_select">
<option value="1">Rossi</option>
<option value="2">Skunk</option>
<option value="3">Ceres</option>
</select>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Information </button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Personal information</h4>
</div>
<div class="modal-body">
// query mysql
<?php (...) SELECT name, address, phone FROM table WHERE id = #my_select ?>
<input type="text" name="name" value="<?php echo $name ?>">
<input type="text" name="address" value="<?php echo $adress ?>">
<input type="text" name="phone" value="<?php echo $phone ?>">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
How to implement a jquery post/get to resolve this?
Try using ajax
The Script for this page would be:
$(function () {
$(document).on("change", "#my_select", function () {
$.ajax({
url: 'path/to/ajaxfile.php',
type: 'GET',
dataType: 'json',
data: {id: $(this).val()},
})
.done(function(response) {
if (response.status) {
$("#myModal").find(".modal-body").html(response.html);
} else {
alert(status.message);
}
})
.fail(function(data) {
alert("Something went wrong please try again later.");
console.log(data.responseText);
});
});
});
And The path/to/ajaxfile.php Code:
/**
* Connect to the database and do other initialization if required.
*
* Assuming Procedual MySQLi.
*/
if (empty($_GET['id'])) {
echo json_encode(array("status" => false, "message" => "There is no User Selected."));
exit;
}
$id = mysqli_real_escape_string($connection, $_GET['id']);
$query = "SELECT name, address, phone FROM table WHERE id = '{$id}'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$inputs = '<input type="text" name="name" value="'. $row['name'] .'">
<input type="text" name="address" value="'. $row['address'] .'">
<input type="text" name="phone" value="'. $row['phone'] .'">';
echo json_encode(array("status" => true, "html" => $inputs));
exit;
} else {
echo json_encode(array("status" => false, "message" => "There is no user with that id."));
exit;
}
I hope this helps.

How to pass value from table to bootstrap modal to PHP?

I've fetched rows from MySQL and looped it with Bootstrap modal and I've made a form in modal from which the data is being sent to PHP script (update.php) with the help of ajax. But in return I am getting the output of last row only.
I need to get the record of specific student with its unique ID.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
while($row = mysqli_fetch_assoc($query_run)){
$id = $row['id'];
$name = $row['name'];
$rollno = $row['rollno'];
$contact = $row['contact'];
$address = $row['address'];
echo "<tr>";
echo '<td>' . $name . '</td>';
echo '<td>' . $rollno . '</td>';
echo '<td>' . $contact . '</td>';
echo '<td>' . $address . '</td>';
echo "<td><button class='btn btn-link btn-custom dis' data-toggle='modal' data-target='#myModal$id'>
EDIT</button> </td>";
echo '</tr>';
?>
<div class="modal fade" id="myModal<?php echo $id; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="rollno" value="<?php echo $rollno; ?>">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="contact" value="<?php echo $contact; ?>">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="address"><?php echo $address; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php }
}?>
</tbody>
</table>
</body>
</html>
JS:
$(document).ready(function(){
var values, url;
$('#updateValues').submit(function(e){
e.preventDefault();
values = $(this).serialize();
url = $(this).attr('action');
$.post(url, values, function(data){
$('#results').html(data);
});
});
});
Update.php:
<?php
if(isset($_POST['name'])&&isset($_POST['rollno'])&&isset($_POST['contact'])&&isset($_POST['address'])){
$id = $_POST['id'];
$name = $_POST['name'];
$rollno = $_POST['rollno'];
$contact = $_POST['contact'];
$address = $_POST['address'];
echo "$id $name $rollno $contact $address";
}else{
echo 'ERROR!';
}
?>
This is not tested/debugged but refactor your code similar to this:
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>
<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Notes:
(1) Create the entire table in a variable, then output the variable all at once.
(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.
(3) Use jQuery to:
(a) detect button click in row
(b) get table data for that row
(c) populate fields in modal
(d) display modal
You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.
(4) Using jQuery to get values from table cells vs. input fields:
(a) .text() - from table cells
(b) .val() - from <input> or <textarea>
Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.

Passing variables to a bootstrap modal form

I have a table that shows film reviews stored in a mysql database. Each of these reviews can be edited with a form that resides within a bootstrap modal. The problem I have is I can't understand how to give each form within the modal a unique ID. At the moment the modal only ever echoes varibales from the first row of reviews in the database. Many thanks.
The Jquery
<script type="text/javascript">
//Edit Review
$(document).ready(function(){
$(".editReview").click(function (e) {
$('#myModal').modal({
e.preventDefault();
var username = $(this).data("username");
var film_id = $(this).data('filmid');
var id = $(this).data('id');
var review = $(this).data('review');
$.post('ajax_editReview.php', {username: username, film_id: film_id, id: id, review: review},
function(data){
$('#myModal').modal('hide');
$("#message").html(data);
$("#review").val('');
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
The Form
<div class="container">
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
<p>
'.$review. '
</p>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-success btn-xs pull-right" data-toggle="modal" data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" data-target="#myModal">edit review</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><h3> Edit your review for '. $movie->getTitle().'</h3></h4>
</div>
<div class="modal-body">
<form>
<div class="editReview">
<div class="form-group">
<label for="review">Review:</label>
<textarea class="form-control" rows="5" id="review" placeholder="'. $review.'" name="review"></textarea>
<input type="hidden" id="username" name="username" value="'.$username.'">
<input type="hidden" id="film_id" name="film_id" value="'. $film_id.'">
<input type="hidden" id="film_title" name="film_title" value="'.$movie->getTitle.'">
<input type="hidden" id="id" name="id" value="'.$id.'">
</div>
<button type="submit" id="FormSubmitReview" data-dismiss="modal" class="btn btn-danger btn-sm pull-right">Save Review</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>
You need to have the modal only once on your page and it seems like you a creating a new one for every review, you don't need to do that, just output it once.
You then need to use the event show.bs.modal like so.
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var username = button.data("username");
var film_id = button.data('filmid');
var id = button.data('id');
var review = button.data('review');
....
});

Submit INPUT to the database to return as a Table PHP jQuery MySQL

I'm trying to refresh a data input into an INPUT through a form and then SUBMIT this to the database to return it as a table on the same page. I want it to do this without showing the refresh of the page.
This is what I have currently. When I put data into any of the INPUT fields and click SUBMIT nothing happens and nothing shows for an error.
<?php
session_start();
error_reporting (E_ALL);
require '../core/cnn.php';
if(isset($_POST['submitsearchprojno'])) {
$searchprojno = $_POST["searchprojno"];
}
if(isset($_POST['submitsearchadd'])) {
$searchaddress = $_POST["searchaddress"];
}
if(isset($_POST['submitsearchpc'])) {
$searchpostcode = $_POST["searchpostcode"];
}
$searchpostcode = mysql_real_escape_string($searchpostcode);
$searchaddress = mysql_real_escape_string($searchaddress);
$searchprojno = mysql_real_escape_string($searchprojno);
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Search Projects</h4>
</div>
<div class="modal-body">
<form class="modal-form" id="searchform" name="searchform" action="" method="post">
<div class="form-group">
<label class="col-md-4 control-label">Project Number</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchprojno" id="searchprojno" placeholder="Enter Project Number">
</div>
<button type="submit" class="btn blue" id="submitsearchprojno" name="submitsearchprojno" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchaddress" id="searchaddress" placeholder="Enter Address">
</div>
<button type="submit" class="btn blue" id="submitsearchadd" name="submitsearchadd" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Postcode</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchpostcode" id="searchpostcode" placeholder="Enter Postcode">
</div>
<button type="submit" class="btn blue" id="submitsearchpc" name="submitsearchpc" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered table-advance table-hover">
<thead>
<tr>
<th class="col-md-9"><i class="fa fa-list-alt"></i> Address</th>
<th class="col-md-3"></th>
</tr>
</thead>
<tbody>
<tr>
<?php $searchrs = mysql_query("SELECT ProjectNo, CONCAT(COALESCE(HouseNoName, ''), ' ', COALESCE(StreetName, ''), ' ',
COALESCE(TownOrCity, ''), ' ', COALESCE(Postcode, '')) AS Display, PropID, AreaID, AWGMember, Householder, HouseNoName,
StreetName, TownOrCity, Postcode, ContactTelephone, AlternatePhone, Email, PropertyTenure, PropertyNotes
FROM prop_property
WHERE IsActive = 1
AND (Postcode = '".$searchpostcode."'
OR StreetName = '".$searchaddress."'
OR ProjectNo = '".$searchprojno."')
") or die(mysql_error());
$checkrs = mysql_query("SELECT * FROM prop_property WHERE IsActive = 0");
if(!mysql_num_rows($checkrs) > 0) {
echo '<td> No record found!</td><td></td>';
}
else {
while ($results = mysql_fetch_array($searchrs)) {
echo '
<td id="displayadd">'.$results['Display'].'</td>
<td>
<form action="../jobdetails.php" method="post">
<input type="hidden" name="searchhouse" value=" '.$results['HouseNoName'].'" >
<input type="hidden" name="searchstreet" value=" '.$results['StreetName'].'" >
<input type="hidden" name="searchtown" value=" '.$results['TownOrCity'].'" >
<input type="hidden" name="searchpostcode" value=" '.$results['Postcode'].'" >
<input type="hidden" name="searchpropid" value=" '.$results['PropID'].'" >
<input type="hidden" name="searchprojectno" value=" '.$results['ProjectNo'].'" >
<button type="submit" class="btn default btn-xs blue-stripe" id="viewsearch" name="viewsearch">View Address</button>
</form>
</td>';
}
}?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</form>
<div class="modal-footer right">
<button type="button" data-dismiss="modal" class="btn default">Cancel</button>
</div>
<script type="text/javascript">
$(function(){
$('#searchform').on('submit', function(e){
e.preventDefault();
//alert($('#searchpostcode').val())
$.post('includes/jobdetailssearch.php',
$('#searchform').serialize(),
function(data, status){
$('.table-responsive #displayadd').html(data.Display);
//$("#table-responsive td").last().append(data);
console.log("done");
}).fail(function () {
console.log("fail");
});
});
});
</script>
How can I get it to POST the INPUT to the database and return in the table?

Categories