How to make the edit modal using ajax and php - php

Im having problem when implementing edit function where I can edit the role of the user
Here is the button that will open the modal
<button type="button" id="edit" name="edit" class="btn btn-outline-warning" data-id="'.$row["id"].'">EDIT</button>
Here is the modal code
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="">
<div class="form-group">
<label for="userName" class="col-form-label">Username:</label>
<input type="text" class="form-control border-danger" id="userName" readonly style="background-color: #2A3038">
</div>
<div class="form-group">
<label for="user_type" class="col-form-label">User Type:</label>
<select class="form-control border-success" id="user_type">
<option value="user">User</option>
<option value="contributor">Contributor</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<input type="hidden" id="user_id" name="user_id">
<button type="submit" id="update" name="update" class="btn btn-success">Update</button>
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ajax
$(document).on('click', '#edit', function(){
var user_id = $(this).attr("data-id");
$.ajax({
url:"/auth/action",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#editModal').modal('show');
$('#userName').val(data.userName);
$('#user_type').val(data.user_type);
$('#user_id').val(user_id);
}
})
});
PHP where the action happens
if($_POST["action"] == 'update')
{
$query = 'UPDATE `users` SET username = :username, user_type = :user_type WHERE id = :id';
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $_POST['user_id'],
':username' => $_POST['userName'],
':user_type' => $_POST['user_type']
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo '<div class="alert alert-fill-warning" role="alert">User type changed!<div>';
}
}
and also I have a function for fetch which I named it load_user_data()
Here is the for the datatype json
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connect->prepare(
"SELECT * FROM users WHERE id = '".$_POST["user_id"]."' LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["userName"] = $row["username"];
$output["user_type"] = $row["user_type"];
}
echo json_encode($output);
}
The problem Im having is that the PHP action code is not working or is there anything wrong with my code? but I dont have probelm with displaying the data in the modal except if i submit the change there is no function happening

Your ajax data property is missing a lot of parametars:
....ajax....
data: {user_id: user_id, userName: username here,user_type:set type here, action: 'update'}
You need to add edit id to your update button
Also you need to add userdata to your ajax response, currently you are using data.userName etc. but you didnt put that in the response
You can find more info on how to properly return json response here:
Returning JSON from a PHP Script

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="">
<div class="appenddata">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="update" name="update" class="btn btn-success">Update</button>
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).on('click', '#edit', function(){
$('#editModal').modal('show');
var user_id = $(this).attr("data-id");
$.ajax({
url:"/auth/action",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$(".appenddata)".html(data);
}
})
});
</script>
<?php
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connect->prepare(
"SELECT * FROM users WHERE id = '".$_POST["user_id"]."' LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
$user_array=array("user","contributor");
?>
<input type="hidden" id="user_id" name="user_id" value="<?= $_POST["user_id"]; ?>">
<div class="form-group">
<label for="userName" class="col-form-label">Username:</label>
<input type="text" class="form-control border-danger" id="userName" value="<?= $result[0]['username']; ?>" readonly style="background-color: #2A3038">
</div>
<div class="form-group">
<label for="user_type" class="col-form-label">User Type:</label>
<select class="form-control border-success" id="user_type">
<?php
if($user_array!=NULL)
{
foreach($user_array as $data)
{
if($data==$result[0]['username'])
{
$selected='selected="selected"';
}
else
{
$selected='';
}
?>
<option value="<?= $data; ?>"><?= ucwords($data); ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}

Related

how to display data in input tag after selecting in select tag value?

I want to achieve after selecting in my select tag, it will display a input tag in my modal and that has been fetch in other table in database.
totalfees.php
if(isset($_POST["year"]))
{
$output = '';
$query = "SELECT total_fees FROM manage_fees WHERE year_lvl = '".$_POST["year"]."'";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output .= '
<input type="text" class="form-control" id="tf" name="tf" readonly="readonly" value="'.$row["total_fees"].'">
';
}
echo $output;
}
gettotal.js
$(document).ready(function(){
$('#year').click(function(){
var year = $(this).attr("year");
$.ajax({
url:"../include/assessment.php",
method:"post",
data:{year:year},
success:function(data){
$('#total_fees').html(data);
}
});
});
assessment.php
<div class="modal fade" id="fee_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Assess Student</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" action="officer_studentAssessment.php" id="reg">
<div class="form-group">
<label for="year">Year</label>
<select class="form-control" id="year" name="year" required>
<?php
$result = $connect->query("SELECT * FROM year_lvl") or die($connect->error());
while($row = $result->fetch_assoc()):
?>
<option value="<?php echo $row['year']; ?>"><?php echo $row["year"]; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group" id="total_fees">
<label for="tf">Total fees</label>
</div>
<div class="modal-footer">
<button class="btn btn-success" name="create" id="create" type="submit">Create</button>
</div>
</form>
</div>
</div>
</div>
</div>
in totalfees.php the output should be display on the DIV tag where id = total_fees, the problem is after I click the select tag the DIV disappears
<div class="form-group" id="total_fees">
<label for="tf">Total fees</label>
</div>
add
<scritp>
let selectval = document.getElementById('selectId');
let val =document.getElementById('yourId');
let val.value = selectval
</script>
in slectId add id of your select input and in yourId add id of input field where you would like to add the data
Looks like a wrong-word typo.
In gettotal.js, in your ajax code block, you are calling out to the wrong url.
Instead of:
url:"../include/assessment.php",
try:
url:"../include/totalfees.php",
Also, you might want to change:
$('#year').click(function(){
to
$('#year').change(function(){

CRUD either edit or delete work, together will fail

I am developing a CRUD function based on bootstrap and php. If click edit button, popup windows will be shown and data can edit and update. If click delete button, popup windows will be shown with data but only allow to confirm delete . I dont know why if run it individually only contains one part of code, the program is running properly. But if put both functions code together, only edit function work, and delete function will not shown any data in the popup windows. Also it is strange that when click confirm delete, it is not direct to delete sql statement (delcatsql.php), but direct to update sql(editcatsql.php). Can advice what is wrong?? Thanks!
**manage_categories.php**
<tbody>
<?php
require_once 'source/db_connect.php';
$sql = "SELECT * FROM category";
$result = mysqli_query($link, $sql);
$i=0;
if ($result->num_rows > 0) {
//output data of each row
while ($row = $result->fetch_assoc()) {
$i = $i + 1;
?>
<tr>
<td><?php echo $row['catid']; ?></td>
<td><?php echo $row['catname']; ?> </td>
<td> <button type="button" id="editcatbtn" class="btn btn-primary
editcatbtn">edit</button> </td>
<td> <button type="button" id="delcatbtn" class="btn btn-danger delcatbtn"
>Delete</button> </td>
</tr>
<?php }
}
?>
<script>
$(document).ready(function () {
$(' .delcatbtn').on('click', function() {
$('#delcatmodel').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#catid').val(data[0]);
$('#catname').val(data[1]);
});
});
</script>
<script>
$(document).ready(function () {
$(' .editcatbtn').on('click', function() {
$('#editcatmodel').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
bootstrap
$('#catid').val(data[0]);
$('#catname').val(data[1]);
});
});
</script>
</tbody>
</table>
</div>
<?php
//Categpry Form
include_once("editcatmodel.php");
include_once("delcatmodel.php");
include_once("editcategory.php");
?>
</body>
**editcatmodel.php**
<!-- edit Model -->
<div class="modal fade" id="editcatmodel" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel2" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel2">Edit Category</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="editcatsql.php" method="POST">
<div class="modal-body">
<input type="hidden" name="editcatid" id="catid">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="editcatname" id="catname" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="editcategory" class="btn btn-primary">Edit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
editcatsql.php
<?php
include_once 'source/session.php';
require_once 'source/db_connect.php';
?>
<?php
$username = 'root';
password = '';
$dsn = 'mysql:host=localhost; dbname=pos';
$link = mysqli_connect("localhost", "root", "", "pos");
if (isset($_POST['editcategory'])) {
$tempcatname = $_POST[('editcatname')];
$tempcatid = $_POST[('editcatid')];
// write edit query
$sql = "UPDATE category SET catname='$tempcatname' WHERE catid='$tempcatid'" ;
$result = $conn->query($sql);
if(! $result )
{
die('Could not update data: ' . mysql_error());
}
header('location: manage_categories.php');
}
?>
**delcatmodel.php**
<!-- Delete Model -->
<div class="modal fade" id="delcatmodel" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel2" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel2">Confirm Delete Category?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="delcatsql.php" method="POST">
<div class="modal-body">
<input type="hidden" name="delcatid" id="catid">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="delcatname" id="catname" class="form-control" disabled>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="deletecategory" class="btn btn-primary">Delete2</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
delcatsql.php
<?php
include_once 'source/session.php';
require_once 'source/db_connect.php';
?>
<?php
$username = 'root';
$password = '';
$dsn = 'mysql:host=localhost; dbname=pos';
$link = mysqli_connect("localhost", "root", "", "pos");
if (isset($_POST['deletecategory'])) {
$tempcatname = $_POST[('delcatname')];
$tempcatid = $_POST[('delcatid')];
// write delete query
//$sql = "delete from category where catid='$tempcatid'" ;
$sql = "delete from category where catid='$tempcatid'" ;
$result = $conn->query($sql);
if(! $result )
{
die('Could not update data: ' . mysql_error());
}
header('location: manage_categories.php');
}
?>

Ways to get id to use in modal for updating database in php

So my purpose is to get the ID from a database and making the id ready to be used for modal. I know that I can use input type=hidden but I don't know for sure it is safe because in inspect element, user can edit it. I'm thinking also of session but I don't have any idea how can I do it. So what are the ways I can do to make the id not editable after submitting? Or how can i put it in array and match the id? Here is my code I used
class.names.php
public function getAllNames()
{
$obj = new Db();
$stmt = $obj->connect()->query("SELECT * FROM persons");
while ($person = $stmt->fetch())
{
echo "<tr>";
echo "<td>".$person['first_name']."</td>";
echo "<td>".$person['last_name']."</td>";
echo "<td><a id=\"".$person['person_id']."\"type=\"button\" data-target-toggle=\"modal\" data-target=\"#edit-name-modal\" class=\"btn btn-danger edit_data\" href=\"#\">Update</a></td>";
echo "</tr>";
}
}
names.js
$(document).on('click', '.edit_data', function(){
var person_id = $(this).attr("id");
$.ajax({
url:"/data/updatename.php",
method:"POST",
data:{person_id:person_id},
dataType:"json",
success:function(data){
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#person_id').val(data.person_id);
$('#edit-name-modal').modal('show');
}
});
});
updatename.php
<?php
include_once 'db.php';
if(isset($_POST["person_id"]))
{
$person_id = $_POST["person_id"];
$object = new Dbc();
$stmt = $object->connect()->prepare("SELECT * FROM persons WHERE person_id=?");
$stmt->execute([$person_id]);
$profile_info = $stmt->fetch();
echo json_encode($profile_info);
}
?>
namelist.php
<div class="modal fade" id="edit-name-modal" name="edit-name" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="POST" enctype="multipart/form-data" action="namelist.php">
<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">Update Name's List</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>First Name</label>
<input type="text" id="first_name" name="first_name" class="form-control">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" id="last_name" name="last_name" class="form-control">
</div>
<input type="hidden" id="person_id" name="person_id">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>

internal server error 500 with jquery.min.js

I am a novice to PHP. Now I am building a simple login-logout system. While trying to log in the system, I got the Internal Server Error with jquery.min.js:4. Here is my code:
Index:
<!-- Login Form -->
<form method="post" id="loginForm">
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="#loginHeading" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="loginHeading">Login Form</h4>
</div>
<div class="modal-body">
<div id="loginMessage"></div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="pass">Password: </label>
<input type="password" id="pass" name="pass" class="form-control" required>
</div>
<div class="row">
<div class="checkbox" >
<div class="pull-left" style="padding-left:20px">
Forget password?
</div>
<label class="pull-right" style="padding-right:20px"><input type="checkbox" name="remember" value=""> Remember me</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success pull-left" data-dismiss="modal" data-toggle="modal" data-target="#signUp">Register</button>
<button type="submit" class="btn myBtn">Login</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Script:
$("#loginForm").submit(function(event) {
event.preventDefault();
var dataPost= $(this).serializeArray();
$.ajax({
url: '4-logIn.php',
type: 'POST',
data: dataPost,
success:function(data){
if (data == "success") {
window.location("mainPageLogin.php");
}
else {
$("#loginMessage").html(data);
}
},
error: function(data){
$('#loginMessage').html('<div class="alert alert-danger"><h5>Error in connection with loginForm</h5></div>');
}
});
});
4-login.php:
``
<?php
session_start();
include '0-connection.php';
$error='';
$email=filter_var($_POST["email"],FILTER_SANITIZE_EMAIL);
$pass=filter_var($_POST["pass"],FILTER_SANITIZE_STRING);
// Query
$email=mysqli_real_escape_string($link,$email);
$pass=mysqli_real_escape_string($link,$pass);
$pass=hash('sha256',$pass);
$sql="SELECT * FROM users WHERE email='$email' AND password='$pass' AND activation='activated'";
$result=mysqli_query($link, $sql);
if (!$result) {
echo "<div class='alert alert-danger'>Error running the query to take user login</div>";
exit;
}
$count= mysqli_num_rows($result);
if ($count !== 1) {
$error="<div class='alert alert-danger'><strong>ERROR:</strong> Wrong username or password. Please try again or Do you want to <a href='#' data-dismiss='modal' data-target='#signUp' data-toggle='modal'>Sign up</a></div>";
echo $error;
}
else {
// Set session
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id']=$row['user_id'];
$_SESSION['username']=$row['username'];
$_SESSION['email']=$row['email'];
// Check remember me Box
if (empty($_POST['remember'])) {
echo "success";
}
else {
}
}
?>
This is my error:
demonstration
web response
Please be more specific in your answer because I am very new in programming. Thanks for reading.
Error in 4-logIn.php, if (!result) { must be changed as if (!$result) {

Bootstrap form Add new record using AJAX and PHP

i've tried looking at the source code and changing this but still have no luck! Hope someone can spot the mistake i've made.
Im basically just trying to submit a form with just 1 input field for now using AJAX and PHP to post using PDO method.
Here is my code:
Connection to database
<?php
define('HOST', 'localhost');
define('DB_NAME','test');
define('USER','root');
define('PASS','');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Problem connecting to database, contact admin';
}
?>
Bootstrap Form
<div class="modal fade" id="add_new_record_modal" 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">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
AJAX Script
$(document).ready(function(){
$('#myform').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "insert.php",
type: "POST",
data: data,
success: function( data )
{
alert( data );
},
error: function(){
alert('ERROR');
}
});
return false;
});
});
insert.php Script
<?php
require_once('config.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$sql = 'INSERT INTO people(name) ';
$sql .= ' VALUES (:name)';
try {
$query = $bd->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
if($query->execute()){
echo "recorded added sucessfully";
}else{
echo "Problem adding new record";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
In your html code, you don't have any form. So you can't directly use .submit() or .serialize()
Consider closing you form elements within <form>
Change your html to this:
<div class="modal fade" id="add_new_record_modal" 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">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
Update:
Add name attribute in input tag.
Serialize labels items by its name attribute.
Try to read about submit() to fully understand how it works: https://api.jquery.com/submit/
You are not using the <form> tag, so submit() doesn't catch any event.
Try wrapping your input and buttons in the same form tag, with id=myform and try again.
Also you are not using event.preventDefault(), without which the page will be refreshed.

Categories