Button Add with modal ajax - php

I'm trying to add a button to add a row in a table adding the values also in a database but when i click the button it refresh my page and doesn't add any row and in my database doesn't add any values.
This is the html form:
<div class="modal fade" id="modaladdWork" 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="modaladdWorkLabel">New Work</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form name="formaddWork">
<div class="modal-body">
<div class="container w-75">
<select id="roleaddWork" name="role" class="form-control" aria-label="Role" aria-describedby="basic-addon1">
<option>Direttore</option>
<option>Vice Direttore</option>
<option>Capo Settore</option>
<option>Dipendente</option>
<option>Stagista</option>
</select> <br>
<input type="number" id="yearaddWork" name="year" min="1900" class="form-control" placeholder="Year" aria-label="Year" aria-describedby="basic-addon1">
<br/>
<input type="text" id="placeaddWork" name="place" class="form-control" placeholder="Place" aria-label="Place" aria-describedby="basic-addon1">
<br />
<?php
$query = "select * from company;";
$result=mysqli_query($connessione, $query);
echo mysqli_error($connessione);
if(mysqli_num_rows($result) > 0){
echo "<div style='float:left';><select id='companyaddWork' name='company' class='form-control' aria-label='Company' aria-describedby='basic-addon1'>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<option>".$row["name"]."</option>";
}
echo "</select></div> <div class='modal-footer'><div style='float:right';>
<button type='button' class='btn btn-primary float-right' data-toggle='modal' data-target='#modalCompany'>
Add Company
</button>
</div></div>";
}
else{
echo "Inserisci prima una compagnia";
}
?>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="submitaddWork" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
and this the javascript code :
function openmodal_addWork()
{
$('#modaladdWork').find('.modal-title').text("Add Work row");
$('#modaladdWork').find(':submit').text("Add");
$('#submitaddWork').click(function() {
op_addWork();
});
$('#modaladdWork').modal('show');
}
function op_addWork()
{
role = $('#roleaddWork').val();
year = $('#yearaddWork').val();
place = $('#placeaddWork').val();
company = $('#companyaddWork').val();
$('#modaladdWork').modal('hide');
$.ajax({
type: "POST",
url: "json/Lavoro.php",
data: {
'role': role,
'year': year,
'place': place,
'company': company
},
success: function(data){
console.log(data);
columns = $(button).closest('tr').find('td');
columns[0].innerHTML = role;
columns[1].innerHTML = year;
columns[2].innerHTML = place;
columns[3].innerHTML = company;
}
});
}
and this one the file "Lavoro.php" that is in the folder "json" :
<?php
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
{
header("Location: ../Principale.php");
exit();
}
if(!isset($_COOKIE["id"]))
{
$json_data = array(
'draw' => 0,
'recordsTotal' => 0,
'recordsFiltered' => 0,
'data' => [],
'error' => 'Laravel Error Handler',
);
$json = json_encode($json_data);
echo $json;
exit();
}
include("../DB.php"); //dati configurazione del database
if(isset($_POST["role"]) && isset($_POST["year"]) && isset($_POST["place"]) && isset($_POST["company"]))
{
$role = mysqli_real_escape_string($connessione, $_POST["role"]);
$year = mysqli_real_escape_string($connessione, $_POST["year"]);
$place = mysqli_real_escape_string($connessione, $_POST["place"]);
$company = mysqli_real_escape_string($connessione, $_POST["company"]);
$result=mysqli_query($connessione,"select company_id from company where name='".$company."';");
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$comp_id=$row[0];
$eeid=$_COOKIE['id'];
$result = mysqli_query($connessione, "INSERT into WORK_EXPERIENCE (role,year,place,company_id,user_id) VALUES ('$role','$year','$place','$comp_id,'$eeid')");
$json_data = array(
//"id" => $id,
"result" => 1
);
$json = json_encode($json_data);
echo $json;
}
?>
What i'm doing of wrong?

Solved. In this line :
$result = mysqli_query($connessione, "INSERT into WORK_EXPERIENCE
(role,year,place,company_id,user_id) VALUES
('$role','$year','$place','$comp_id,'$eeid')")
there was no summit in $comp_id.

Related

How yo insert data with image in AngularJs and PHP mysql

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

Get ID to follow from one page to another

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.

jQuery PHP only works with 3 parameters

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 ;)

Printing JSON (from a php) through ajax to a bootstrap modal

Now this one seems a little complicated and maybe I have got myself into more than I can manage but it seems the only way I can achieve what I need.
I am a complete novice and am going at this blindly for a project I'm working on (this is the most complicated thing in the whole project) so any help would be much appreciated!
I basically have a bootstrap webpage, this webpage displays a users list (from php in a while loop). What I need the user to be able to do is select a user from this and edit the details in a form in a bootstrap modal.
So far I have everything working, modal loading etc and from various sources online have wrangled JSon but I've never learnt it and am way out of my depths. Currently it is printing '[object HTMLCollection]' in each field.
Firstly here is the HTML for the modal & list:
Modal (This comes up perfectly)
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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>
<h2 class="modal-title" id="editModalLabel"></h2>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="username" class="control-label">Username:</label>
<input type="text" name="username" class="form-control" id="username"></input>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label for="password" class="control-label">Password:</label>
<div class="input-group">
<span class="input-group-btn">
<input type="button" class="form-control" value="Change Password" onClick="changeRandomPassword();">
</span>
<input type="text" name="password" class="form-control" id="password" value="" required></input>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="firstName" class="control-label">First Name:</label>
<input type="text" name="firstName" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label">Surname:</label>
<input type="text" name="lastName" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="jobTitle" class="control-label">Job Title:</label>
<input type="text" name="jobTitle" class="form-control" id="jobTitle">
</div>
<div class="form-group">
<label for="TaskTeam" class="control-label">Task Team:</label>
<input type="text" name="TaskTeam" class="form-control" id="TaskTeam">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success">Submit Changes</button>
</div>
</div>
</div>
</div>
Here is the php list: (again no trouble here)
<?php
include("dbconnect.php");
$dbQuery= mysql_query("SELECT * FROM users ORDER BY lastName ASC;");
while($dbRow = mysql_fetch_array($dbQuery))
{
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
$admin = $dbRow['admin'];
echo '<tr>';
echo '<td>';
echo '<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>';
echo '</td>';
echo '<td>'.$firstName.'</td>';
echo '<td>'.$lastName.'</td>';
echo '<td>'.$jobTitle.'</td>';
echo '<td>'.$userteam.'</td>';
echo '<td>'.$admin.'</td>';
echo '<td>';
echo '<a href="deleteUser.php?id='.$userID.'">';
echo '<button type="button" name="delete_row" id="delete_row" class="close">';
echo '<span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash">';
echo '</span>';
echo '<span class="sr-only">';
echo 'Delete';
echo '</span>';
echo '</button>';
echo '</a>';
echo '</td>';
echo '</tr>';
}
echo mysql_error();
mysql_close();
?>
Here is where the problem must lay:
<script>
$('#editUserModal').on('show.bs.modal', function (event)
{
var button = $(event.relatedTarget)
var recipient = button.data('user')
var modal = $(this)
modal.find('.modal-title').text('Edit ' + recipient + "'s details.")
$(function ()
{
$.ajax(
{
type: 'GET',
url: "getUser.php?id=",
data: 'recipient',
dataType: "json",
success: function(data)
{
var obj = JSON.parse(data);
$.each(obj, function(key, val)
{
console.log(val);
var id = data[0];
var firstName = data[1];
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
});
}
})
})
modal.find('.modal-body #firstName').val(firstName)
modal.find('.modal-body #lastName').val(lastName)
modal.find('.modal-body #username').val(username)
modal.find('.modal-body #password').val(password)
modal.find('.modal-body #jobTitle').val(jobTitle)
modal.find('.modal-body #TaskTeam').val(TaskTeam)
})
</script>
Lastly here is php file to get the user details: (This works too but only is done manually- This is the bulk of it excluding passwords etc)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$userid = intval($_GET['id']);
$sql="SELECT * FROM users WHERE id = $userid";
$result = $conn->query($sql);
/*
$user = array();
while ($row = mysql_fetch_array($result)) {
$details = array(
"username" => $row['username'],
"firstName" => $row['firstName'],
"lastName" => $row['lastName'],
"taskTeam" => $row['taskTeam']
);
$user[] = $details;
}
echo json_encode($user);
$conn->close();
*/
if ($result->num_rows > 0) {
// output data of each row
$array = array();
while($row = $result->fetch_assoc()) {
array_push($array, $row);
}
echo json_encode($array);
} else {
echo "0 results";
}
$conn->close();
Sorry for lack of Mysqli I know this is the latest standard and am currently implementing it in this project.
Any help would be great! Thanks
The problem with your code is here:
var obj = JSON.parse(data);
$.each(obj, function(key, val)
{
console.log(val);
var id = data[0];
var firstName = data[1];
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
});
You've already told your AJAX call that you are expecting JSON back from your PHP script. You did this with dataType: "json". So there is no reason to do this here: var obj = JSON.parse(data);. Since you told your AJAX call you are going to receive JSON back, it automatically parses it for you when the PHP script completes.
To access the data simply use the . syntax. For example, data.firstName
Also, you may need to need to change this line in your PHP file from
echo json_encode($array);
to
header('Content-Type: application/json');
echo json_encode($array);
Also, your PHP script needed some cleaning up:
<?php
include("dbconnect.php");
$dbQuery = mysql_query("SELECT * FROM users ORDER BY lastName ASC;");
while ($dbRow = mysql_fetch_array($dbQuery)) {
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
$admin = $dbRow['admin'];
echo '
<tr>
<td>
<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>
</td>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
<td>'.$jobTitle.'</td>
<td>'.$userteam.'</td>
<td>'.$admin.'</td>
<td>
<a href="deleteUser.php?id='.$userID.'">
<button type="button" name="delete_row" id="delete_row" class="close">
<span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash"></span>
<span class="sr-only">Delete</span>
</button>
</a>
</td>
</tr>';
}
echo mysql_error();
mysql_close();
?>

Using AJAX to call a PHP (through MSQL) and fill a bootstrap modal

I have a user list on an HTML table, when I click an entry I have a modal loading through AJAX which should fill a form out with all the relevant information from that user. Information can then be changed and submitted via a change.
I cannot get past getting the modal to load and cannot get data to be loaded into the model.
Here is the script:
<script>
$('#editUserModel').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('userID')
$(function ()
{
$.ajax({
url: 'getUser.php?id=',
data: "recipient",
dataType: 'json',
success: function(data)
{
var id = data[0]; //get id
var firstName = data[1]; //get name etc...
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
var modal = $(this)
modal.find('.modal-body input').html(username)
}
});
});
})
</script>
Here is the PHP which lists the users (this works and when I click the Edit button a modal loads however the modal is grayed out and shows no underlying data)
<?php
include("dbconnect.php");
$dbQuery= mysql_query("SELECT * FROM users ORDER BY jobTitle ASC;");
while($dbRow = mysql_fetch_array($dbQuery))
{
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
echo '<tr>';
echo '<td>';
echo '<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModel" data-userID='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>';
echo '</td>';
echo '<td>'.$firstName.'</td>';
echo '<td>'.$lastName.'</td>';
echo '<td>'.$jobTitle.'</td>';
echo '<td>'.$userteam.'</td>';
echo '<td></td>';
/*
echo '<td>';
echo '</td>';
*/
echo '</tr>';
}
echo mysql_error();
mysql_close();
?>
Here is the modal div:
<div class="modal fade" id="editUserModel" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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="editModalLabel"></h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="username" class="control-label">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="password" class="control-label">Password:</label>
<input type="text" class="form-control" id="password">
</div>
<div class="form-group">
<label for="firstName" class="control-label">First Name:</label>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label">Surname:</label>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="jobTitle" class="control-label">Job Title:</label>
<input type="text" class="form-control" id="jobTitle">
</div>
<div class="form-group">
<label for="TaskTeam" class="control-label">Task Team:</label>
<input type="text" class="form-control" id="TaskTeam">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Submit Changes</button>
</div>
</div>
</div>
</div>
And here is the php file which retrieves the user data:
<?php
$userID = intval($_GET['id']);
include("dbconnect.php");
$sql="SELECT * FROM users WHERE id = $userID";
$result = mysql_query($sql);
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_close();
?>
I don't fully understand PDO, I'm not sure where the problem is.
Rahter than mysql use mysqli. Also, the problem is happening because you need to iterate through your rows result. Try this:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$userID = intval($_GET['id']);
$sql="SELECT * FROM users WHERE id = $userID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$array = array();
while($row = $result->fetch_assoc()) {
array_push($array, $row);
}
echo json_encode($array);
} else {
echo "0 results";
}
$conn->close();
Then in your JS, replace the contents of .success with this:
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function(key, val) {
console.log(val);
//add your functions here
/*
var id = data[0]; //get id
var firstName = data[1]; //get name etc...
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
var modal = $(this)
modal.find('.modal-body input').html(username)
*
*/
});
}

Categories