I am trying to create a page where incomes and expenses can be tracked. However, once I click the send button on the page, ajax returns success only the first time, so the alert(successNum) function works only 50% of the time.
This is the index.php ,where the ajax call is.
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script>
<script src="https://kit.fontawesome.com/2c66dc83e7.js" crossorigin="anonymous"></script>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Arpad Media IO</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 align=center>Budget</br><button class="btn btn-warning" data-toggle="modal" data-target="#budgetModal">Add entry</button></h1>
<table class="budget_table">
<tr><td><h3>Incomes</h3></td>
<td><h3>Expenses</h3></td></tr>
<tr>
<td><table class="income_table money_table"><tr>
<?php
$query = "SELECT * FROM `main_budget` WHERE `Type` = 'INC' ORDER BY `Date` DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo '<tr><td><h3 class="text text-success">+'.$row["Amount"].' Ft</h3><h5>'.$row["Description"].'</h5></td></tr>';
}
?>
</tr></table></td>
<td><table class="expense_table money_table "><tr>
<?php
$query = "SELECT * FROM `main_budget` WHERE `Type` = 'EXP' ORDER BY `Date` DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo '<tr><td><h3 class="text text-danger">-'.$row["Amount"].' Ft</h3><h5>'.$row["Description"].'</h5></td></tr>';
}
?>
</tr></table></td>
</tr></table>
<?php
$query = "SELECT * FROM `main_budget` ORDER BY `Date` DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$TotalMoney=0;
foreach($result as $row){
if ($row["Type"]=="EXP"){
$row["Amount"]=$row["Amount"]*-1;
}
$TotalMoney += $row["Amount"];
}
echo '<h4 class="finalValue">Total: '.$TotalMoney.' Ft</h4>';
$connect=null;
?>
<div class="modal fade" id="budgetModal" tabindex="-1" role="dialog" aria-labelledby="budgetModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Entry</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="sendBudgetForm">
<select class="form-control" id="budgetTypeSelect">
<option value="INC">Income</option>
<option value="EXP">Expense</option>
</select>
<input class="form-control" id="budgetName" type="text" placeholder="Title"></input>
<input class="form-control" id="budgetValue" type="number" placeholder="Amount"></input>
<input type="hidden" id="userName" value=<?php echo $_SESSION["UserUserName"];?>></input>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input type="submit" id="sendBudget" class="btn btn-primary" value="Send"></input>
</form>
</div>
</div>
</div>
</div>
</html>
<script>
$('#sendBudgetForm').on('submit', function () {
var bType = $( "#budgetTypeSelect").val();
var bName = document.getElementById('budgetName').value;
var bVal = document.getElementById('budgetValue').value;
var bUser = document.getElementById('userName').value;
$.ajax({
url:"budgetHandler.php",
type:"POST",
data:{bType:bType, bName:bName, bVal:bVal, bUser:bUser},
success:function(successNum){
alert(successNum);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
})
});
</script>
The budgetHandler.php looks like this:
<?php
session_start();
$connect = new PDO("mysql:host=localhost;dbname=budget", "root", "password");
if(isset($_POST["bVal"]))
{
$query="INSERT INTO `main_budget` (`Author`, `Type`, `Description`, `Amount`)
VALUES (:author, :typee, :descriptionn, :amount)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':author' => $_POST['bUser'],
':typee' => $_POST['bType'],
':descriptionn' => $_POST['bName'],
':amount' => $_POST['bVal']
)
);
$connect=null;
echo "1";
}
?>
I've tried adding the datatype:'text' tag, but it didn't help.
Changing the event binding to $('#sendBudgetForm').on('submit', function (e) { then adding e.preventDefault(); $('#budgetModal').modal('hide'); and adding location.reload(); to the ajax call's success function seems to fix my error!
Related
I have a CRUD table where I want to display users list with the profile pictures
I'm using AngularJs and Bootstrap
I have added upload file to the form and I'm able to insert to the DB but not able to save the uploaded file to my directory (/uploads)
My index form
<!DOCTYPE html>
<html>
<head>
<title>users</title>
<script src="jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script src="angular-datatables.min.js"></script>
<script src="bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="datatables.bootstrap.css">
</head>
<body ng-app="crudApp" ng-controller="crudController">
<div class="container" ng-init="fetchData()">
<br />
<h3 align="center">user's List</h3>
<br />
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div align="right">
<button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
</div>
<br />
<div class="table-responsive" style="overflow-x: unset;">
<table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
<thead>
<tr><!--data-visible="false"-->
<th width="10%">Image</th>
<th width="35%">First Name</th>
<th width="35%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="name in namesData">
<td>
<img id="{{name.id}}" ng-src="uploads/{{name.photo}}" class="thumbnail" height="50" width="50" >
</td>
<td>{{name.first_name}}</td>
<td>{{name.last_name}}</td>
<td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
<td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="post" ng-submit="submitForm()">
<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">{{modalTitle}}</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" ng-model="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" ng-model="last_name" class="form-control" />
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="photo" ng-model="photo">
<label class="custom-file-label" for="photo">Choose file</label>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="hidden_id" value="{{hidden_id}}" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script>
var app = angular.module('crudApp', ['datatables']);
app.controller('crudController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('fetch_data.php').success(function(data){
$scope.namesData = data;
});
};
$scope.openModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('show');
};
$scope.closeModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('hide');
};
$scope.addData = function(){
$scope.modalTitle = 'Add Data';
$scope.submit_button = 'Insert';
$scope.openModal();
};
$scope.submitForm = function(){
$http({
method:"POST",
url:"insert.php",
data:{'photo':$scope.photo, 'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.form_data = {};
$scope.closeModal();
$scope.fetchData();
}
});
};
$scope.fetchSingleData = function(id){
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'fetch_single_data'}
}).success(function(data){
$scope.photo = data.photo;
$scope.first_name = data.first_name;
$scope.last_name = data.last_name;
$scope.hidden_id = id;
$scope.modalTitle = 'Edit Data';
$scope.submit_button = 'Edit';
$scope.openModal();
});
};
$scope.deleteData = function(id){
if(confirm("Are you sure you want to remove it?"))
{
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'Delete'}
}).success(function(data){
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
};
});
</script>
Insert file which I'm unable to insert images
<?php
//insert.php
include('database_connection.php');
$form_data = json_decode(file_get_contents("php://input"));
$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';
if($form_data->action == 'fetch_single_data')
{
$query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['first_name'] = $row['first_name'];
$output['last_name'] = $row['last_name'];
}
}
elseif($form_data->action == "Delete")
{
$query = "
DELETE FROM tbl_sample WHERE id='".$form_data->id."'
";
$statement = $connect->prepare($query);
if($statement->execute())
{
$output['message'] = 'Data Deleted';
}
}
else
{
if(empty($form_data->first_name))
{
$error[] = 'First Name is Required';
}
else
{
$first_name = $form_data->first_name;
}
if(empty($form_data->last_name))
{
$error[] = 'Last Name is Required';
}
else
{
$last_name = $form_data->last_name;
}
if(empty($error))
{
if($form_data->action == 'Insert')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name
);
$query = "
INSERT INTO tbl_sample
(first_name, last_name) VALUES
(:first_name, :last_name)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
if($form_data->action == 'Edit')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name,
':id' => $form_data->id
);
$query = "
UPDATE tbl_sample
SET first_name = :first_name, last_name = :last_name
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Edited';
}
}
}
else
{
$validation_error = implode(", ", $error);
}
$output = array(
'error' => $validation_error,
'message' => $message
);
}
echo json_encode($output);
?>
Fetch table
<?php
//fetch_data.php
include('database_connection.php');
$query = "SELECT * FROM tbl_sample ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>
I'm using PDO connection
How I can add insert image among the above function
so I have this task to make a CRUD page as an assignment, the only problem is when i click delete on my read page nothing happends. Same in the update where I can fill in the new name but it does'nt connect with my database.
<?php
//inkludering av databaskoppling
require 'databaskoppling.php';
// sql som hämtar alla poster från tabellen 'person' i databasen med en limit på 100 personer
$sql = "SELECT * FROM skadespelare ORDER BY fornamn LIMIT 100;";
// om anslutningen fungerar ska sql köras mot databasen och därefter sparas i $result
$result = $mysqli->query($sql);
// Skriver ut <th>-celler med rubriker för förnamn och efternamn
echo "<th>Förnamn</th><th>Efternamn</th>";
// 2 tomma celler till ändra- och raderalänkarna och avslutande th-celler från föregående rad
echo "<th> </th><th> </th></tr>";
// tbody start
echo "\n<tbody>\n";
// while skriver ut all data som hämtats från tabellen som finns i $resultat
// $myRow är en tillfällig variabel som innehåller data från en rad
while($myRow = $result->fetch_array()) {
echo "<tr>\n";
echo "<td>" . $myRow['fornamn'] . "</td>\n";
echo "<td> " . $myRow['efternamn'] . "</td>\n";
// Här följer de två cellerna för "Ändra" och "Radera"
echo '<td>Ändra</td>' . "\n";
echo '<td>Radera</td>' . "\n";
echo "</tr>\n\n";
}
?>
If you use jquery, you can use AJAX, and I have provide a full code for you as follow,
<?php
require 'databaskoppling.php';
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<table>
<tr>
<th>Förnamn</th>
<th>Efternamn</th>
</tr>
<tbody>
<?php
$sql = "SELECT * FROM timetb;";
$result = $mysqli->query($sql);
while ($myRow = $result->fetch_array()) {
$column_id = $myRow['id'] ;
$column1 = $myRow['column_1'] ;
$column2 = $myRow['column_2'] ;
echo "<tr><td>" . $column1 . "</td>
<td> " . $column2 ."</td>
<td>><button type='button' data-toggle='modal' data-target='#update_modal' class='btn btn-primary' onclick='updateFunction(\"".$column_id."\",\"".$column1."\",\"".$column2."\");'>Update</button></td>
<td><button type='button' class='btn btn-danger' onclick='deleteFunction(\"".$column_id ."\");'>Delete</button></td>
";
}
?>
</tbody>
</table>
<div class="modal" id="update_modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="messages"></div>
<form id="edit_form" method="post" action="update.php">
<div class="form-group">
<label for="field_one">Id</label>
<input type="text" readonly class="form-control" name="edit_id" id="edit_id">
</div>
<div class="form-group">
<label for="field_one">field one</label>
<input type="text" class="form-control" name="field_one" id="field_one">
</div>
<div class="form-group">
<label for="field_two">field two</label>
<input type="text" class="form-control" name="field_two" id="field_two">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function updateFunction(id, col1, col2) {
$("#edit_id").val(id);
$("#field_one").val(col1);
$("#field_two").val(col2);
// submit form function
$("#edit_for").submit(function() {
if (id) {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
//success msg here
}else {
////error msg here
}
}
});
}
return false;
});
}
</script>
</body>
</html>
And Your update.php should like this,
require 'databaskoppling.php';
$valid['success'] = array('success' => false, 'messages' => array());
if ($_POST) {
$id = $_POST['edit_id'];
$field_one = $_POST['field_one'];
$field_two = $_POST['field_two'];
$sql = "UPDATE tablename SET field_one = '$field_one', field_two = '$field_two' WHERE id = '$id'";
$mysqli->query($sql);
if ($connect->query($sql) === true) {
$valid['success'] = true;
$valid['messages'] = "Successfully Updated";
} else {
$valid['success'] = false;
$valid['messages'] ="Error while Editing";
}
}
and delete functions very same.
Think it will be help.
I'm using a comment form with a first name field that is supposed to send to the database with the comments, but for some reason even though I have the column first_name in the database it won't send, any suggestions?
P.S
I am aware of any SQL Injection vulnerabilities but thank you for being concerned! I plan to just focus on this problem before going further.
Thank you for helping!
<?php
session_start();
$loggedIn = false;
if (isset($_SESSION['loggedIn']) && isset($_SESSION['name'])) {
$loggedIn = true;
}
$conn = new mysqli('localhost', '', '', 'profiles2');
function createCommentRow($data) {
global $conn;
$response = '
<div class="comment">
<div class="user">'.$data['name'].' <span class="time">'.$data['createdOn'].'</span></div>
<div class="userComment">'.$data['comment'].'</div>
<div class="reply">REPLY</div>
<div class="replies">';
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id WHERE replies.commentID = '".$data['id']."' ORDER BY replies.id DESC LIMIT 1");
while($dataR = $sql->fetch_assoc())
$response .= createCommentRow($dataR);
$response .= '
</div>
</div>
';
return $response;
}
if (isset($_POST['getAllComments'])) {
$start = $conn->real_escape_string($_POST['start']);
$response = "";
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT $start, 20");
while($data = $sql->fetch_assoc())
$response .= createCommentRow($data);
exit($response);
}
if (isset($_POST['addComment'])) {
$comment = $conn->real_escape_string($_POST['comment']);
$isReply = $conn->real_escape_string($_POST['isReply']);
$commentID = $conn->real_escape_string($_POST['commentID']);
$first_name = $conn->real_escape_string($_POST['first_name']);
if ($isReply != 'false') {
$conn->query("INSERT INTO replies (comment, commentID, userID, createdOn) VALUES ('$comment', '$commentID', '".$_SESSION['userID']."', NOW())");
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id ORDER BY replies.id DESC LIMIT 1");
} else {
$conn->query("INSERT INTO comments (userID, first_name, comment, createdOn) VALUES ('".$_SESSION['userID']."','".$first_name."','$comment',NOW())");
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT 1");
}
$data = $sql->fetch_assoc();
exit(createCommentRow($data));
}
if (isset($_POST['register'])) {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id FROM users WHERE email='$email'");
if ($sql->num_rows > 0)
exit('failedUserExists');
else {
$ePassword = password_hash($password, PASSWORD_BCRYPT);
$conn->query("INSERT INTO users (name,email,password,createdOn) VALUES ('$name', '$email', '$ePassword', NOW())");
$sql = $conn->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
$data = $sql->fetch_assoc();
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
}
} else
exit('failedEmail');
}
if (isset($_POST['logIn'])) {
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id, password, name FROM users WHERE email='$email'");
if ($sql->num_rows == 0)
exit('failed');
else {
$data = $sql->fetch_assoc();
$passwordHash = $data['password'];
if (password_verify($password, $passwordHash)) {
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $data['name'];
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
} else
exit('failed');
}
} else
exit('failed');
}
$sqlNumComments = $conn->query("SELECT id FROM comments");
$numComments = $sqlNumComments->num_rows;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>YouTube Comment System</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
.comment {
margin-bottom: 20px;
}
.user {
font-weight: bold;
color: black;
}
.time, .reply {
color: gray;
}
.userComment {
color: #000;
}
.replies .comment {
margin-top: 20px;
}
.replies {
margin-left: 20px;
}
#registerModal input, #logInModal input {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="modal" id="registerModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Registration Form</h5>
</div>
<div class="modal-body">
<input type="text" id="userName" class="form-control" placeholder="Your Name">
<input type="email" id="userEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="registerBtn">Register</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="logInModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Log In Form</h5>
</div>
<div class="modal-body">
<input type="email" id="userLEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userLPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="loginBtn">Log In</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="col-md-12" align="right">
<?php
if (!$loggedIn)
echo '
<button class="btn btn-primary" data-toggle="modal" data-target="#registerModal">Register</button>
<button class="btn btn-success" data-toggle="modal" data-target="#logInModal">Log In</button>
';
else
echo '
Log Out
';
?>
</div>
</div>
<div class="row" style="margin-top: 20px;margin-bottom: 20px;">
<div class="col-md-12" align="center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/u2O_QyPfdpE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
<div class="form">
<form action="search_page.php" method="post">
<input type="text" name="search" />
<button>Search</button>
</form>
</div>
<div class="row">
<div class="col-md-12">
<form method="POST" action="index.php">
<input type="text" name="first_name" placeholder="First Name...">
<textarea class="form-control" id="mainComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<input type="submit" value="Comment" style="float:right" class="btn-primary btn" onclick="isReply = false;" id="addComment">
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h2><b id="numComments"><?php echo $numComments ?> Comments</b></h2>
<div class="userComments">
</div>
</div>
</div>
</div>
<div class="row replyRow" style="display:none">
<div class="col-md-12">
<textarea class="form-control" id="replyComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<button style="float:right" class="btn-primary btn" onclick="isReply = true;" id="addReply">Add Reply</button>
<button style="float:right" class="btn-default btn" onclick="$('.replyRow').hide();">Close</button>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
var isReply = false, commentID = 0, max = <?php echo $numComments ?>;
$(document).ready(function () {
$("#addComment, #addReply").on('click', function () {
var comment;
if (!isReply)
comment = $("#mainComment").val();
else
comment = $("#replyComment").val();
if (comment.length > 5) {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID
}, success: function (response) {
max++;
$("#numComments").text(max + " Comments");
if (!isReply) {
$(".userComments").prepend(response);
$("#mainComment").val("");
} else {
commentID = 0;
$("#replyComment").val("");
$(".replyRow").hide();
$('.replyRow').parent().next().append(response);
}
}
});
} else
alert('Please Check Your Inputs');
});
$("#registerBtn").on('click', function () {
var name = $("#userName").val();
var email = $("#userEmail").val();
var password = $("#userPassword").val();
if (name != "" && email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
register: 1,
name: name,
email: email,
password: password
}, success: function (response) {
if (response === 'failedEmail')
alert('Please insert valid email address!');
else if (response === 'failedUserExists')
alert('User with this email already exists!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
$("#loginBtn").on('click', function () {
var email = $("#userLEmail").val();
var password = $("#userLPassword").val();
if (email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
logIn: 1,
email: email,
password: password
}, success: function (response) {
if (response === 'failed')
alert('Please check your login details!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
getAllComments(0, max);
});
function reply(caller) {
commentID = $(caller).attr('data-commentID');
$(".replyRow").insertAfter($(caller));
$('.replyRow').show();
}
function getAllComments(start, max) {
if (start > max) {
return;
}
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
getAllComments: 1,
start: start
}, success: function (response) {
$(".userComments").append(response);
getAllComments((start+20), max);
}
});
}
</script>
</body>
</html>
It appears to me that you are making an Ajax call with addComment set to 1, but you are not sending the first_name, you are only sending comment, commentID and isReply.
Your form needs an ID on the first_name
<form method="POST" action="index.php">
<input type="text" name="first_name" id='first_name' placeholder="First Name...">
Then, send the first name value in your addComment ajax call like this:
First, get the value of first_name
var first_name = $("first_name").val()
...
Then add it to ajax call:
data: {
first_name:first_name,
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID
Heyho,
I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.
Maybe someone could figure out where the mistake is...
This is my code:
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</h1>
<div class="col-sm-8">
<div class="well clearfix">
<div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
<span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
<table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
<th data-column-id="employee_name">Name</th>
<th data-column-id="employee_salary">Salary</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id="add_model" class="modal fade">
<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">Add Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_add">
<input type="hidden" value="add" name="action" id="action">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name" name="name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="salary" name="salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="edit_model" class="modal fade">
<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">Edit Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_id" id="edit_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="edit_name" name="edit_name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#employee_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());
} else {
alert('Now row selected! First select row, then click edit button');
}
}).end().find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
alert(conf);
if(conf){
$.post('response.php', { id: $(this).data("row-id"), action:'delete'}
, function(){
// when ajax returns (callback),
$("#employee_grid").bootgrid('reload');
});
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
});
</script>
response.php
<?php
//include connection file
include_once("connection.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Employee($connString);
switch($action) {
case 'add':
$empCls->insertEmployee($params);
break;
case 'edit':
$empCls->updateEmployee($params);
break;
case 'delete':
$empCls->deleteEmployee($params);
break;
default:
$empCls->getEmployees($params);
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getEmployees($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertEmployee($params) {
$data = array();;
$sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' ); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) ) {
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."' WHERE id='".$_POST["edit_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
}
function deleteEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "delete from `employee` WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
}
?>
There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!
Thank you in advance,
Francis
Yes, you just had to delete the field from your database. It was likely marked as NOT NULL, and when you removed the field from the code, INSERT failed trying to insert a null employee_age :)
You should use your browsers developer tools to check the 'Network' tab for the XHR requests that get fired and have a look at the responses of those.
I think you can debug your way to a working solution from there.
You can use other tools like postman to test you AJAX "API" (response.php) but the developer tools of your browser should be more then sufficient for this ;)
i'm currently developing a php license key login which uses pdo with a friend but we need help displaying error messages on the same page as they are currently displayed like this: http://prntscr.com/amrg8k
We're using bootstrap
My config:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'sprx');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('ERRMSG', 'ERROR: SOMETHING IS WRONG!');
try {
$odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch( PDOException $Exception ) {
die(ERRMSG);
}
function error($string)
{
return '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>ERROR:</strong> '.$string.'</div>';
}
function success($string)
{
return '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>SUCCESS:</strong> '.$string.'</div>';
}
define('DIRECT', TRUE);
require 'func.php';
$user = new user;
?>
My Login:
<?php
require 'inc/php/php.php';
if ($user -> LoggedIn())
{
header('Location: index');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="passion">
<meta name="keyword" content="">
<title>Passion | Key System</title>
<!-- CSS -->
<link href="inc/assets/css/bootstrap.css" rel="stylesheet">
<link href="inc/assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<!-- Custom -->
<link href="inc/assets/css/style.css" rel="stylesheet">
<link href="inc/assets/css/style-responsive.css" rel="stylesheet">
<!-- jQuery -->
<script src="inc/assets/js/jquery.js" type="text/javascript"></script>
<script src="inc/assets/js/jquery.maskedinput.js" type="text/javascript"></script>
</head>
<body>
<!-- Main -->
<div id="login-page">
<div class="container">
<form class="form-login" action="" method="post">
<?php
if(isset($_POST['logBtn'])) {
$licensekey = $_POST['licensekey'];
//Is it empty?
if (empty($licensekey) || strlen($licensekey) < 13) {
die(error('Please fill in all fields.'));
}
//Check key
$SQLCheckLogin = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `licensekey` = :licensekey");
$SQLCheckLogin -> execute(array(':licensekey' => $licensekey));
$countLogin = $SQLCheckLogin -> fetchColumn(0);
if (!($countLogin == 1)) {
die(error('License key is invalid.'));
}
//Check if the key is banned
$SQL = $odb -> prepare("SELECT `status` FROM `users` WHERE `username` = :username");
$SQL -> execute(array(':username' => $username));
$status = $SQL -> fetchColumn(0);
if ($status == 1) {
die(error('You are banned'));
}
//Success, log in
$SQL = $odb -> prepare("SELECT * FROM `users` WHERE `licensekey` = :licensekey");
$SQL -> execute(array(':licensekey' => $licensekey));
$keyInfo = $SQL -> fetch();
$_SESSION['licensekey'] = $keyInfo['licensekey'];
$_SESSION['ID'] = $keyInfo['ID'];
header("Location: index");
}
//Start forgot license
if (isset($_POST['doBtn'])) {
$SQLGetInfo = $odb -> prepare("SELECT * FROM `users` WHERE `email` = :email LIMIT 1");
$n = 0;
$SQLGetInfo -> execute(array(':email' => $_POST['email']));
while($row = $SQLGetInfo ->fetch())
{
$showLicense = $row['licensekey'];
$showEmail = $row['email'];
$currentIP = $_SERVER['REMOTE_ADDR'];
$showID = $row['ID'];
//Send Email
$to = $showEmail;
$subject = 'License Key';
$message = 'Hello, you have requested a license key reset.<br>Requested IP: '.htmlspecialchars($currentIP).'<br>Your License Key: '.htmlspecialchars($showLicense).'';
$headers = 'From: admin#example.com' . "\r\n" .'Reply-To: admin#example.com' . "\r\n" .'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>SUCCESS:</strong> Email has been sent!</div>';
++$n;
}
if(0 == $n)
{
echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>ERROR:</strong> Email is invalid</div>';
}
}
?>
<h2 class="form-login-heading">PANEL LOGIN</h2>
<form method="post">
<div class="login-wrap">
<input id="key" class="form-control" name="licensekey" type="text" placeholder="XXXX-XXXX-XXXX" /><script>jQuery(function($){$("#key").mask("****-****-****",{placeholder:"XXXX-XXXX-XXXX"});});</script>
<label class="checkbox">
<span class="pull-right">
<a data-toggle="modal" href="#forgotKey"> Forgot your key?</a>
</span>
</label>
<button class="btn btn-theme btn-block" name="logBtn" type="submit"><i class="fa fa-lock"> </i> LOGIN</button>
<hr>
<div class="registration">
Don't have a key yet?<br/>
<a class="" href="#">
Purchase a key
</a>
</div>
</div> </form>
<div aria-hidden="true" aria-labelledby="forgotKey" role="dialog" tabindex="-1" id="forgotKey" class="modal fade">
<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">Forgot your key ?</h4>
</div>
<form method="post">
<div class="modal-body">
<p>Enter your e-mail address below to receive your key - This process is instant.</p>
<input type="text" name="email" placeholder="Email" autocomplete="off" class="form-control placeholder-no-fix">
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-theme" name="doBtn" type="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</form>
</div>
</div>
<script src="inc/assets/js/jquery.js"></script>
<script src="inc/assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="inc/assets/js/jquery.backstretch.min.js"></script>
<script>
$.backstretch("inc/assets/img/gta-background-blur.jpg", {speed: 500});
</script>
</body>
</html>
Your statement has die(). First remove it.
This die() is causing display of only error message and rest of the page is dying,
Replace
die(error('Please fill in all fields.'));
By
echo error('Please fill in all fields.');