Updating textarea and datetime - php

Well, I have these input fields of date_submitted and remarks. My date_submitted is in a input type of datetime-local and my remarks is in a textarea tag. I have a function where in I can update the data I entered in it.
So here are my problems with examples:
ex. I input 03/03/2018 12:31 AM then click add for it to be added in the database, now when I am going to update it, it just shows this mm/dd/yyyy --:-- -- instead of 03/03/2018 12:31 AM
ex. For the remarks, when I input
Hello
World
then add it then update it, it shows in the textarea field this
Hello //insert br tag
World //insert br tag
so my questions are how am I gonna remove the br tags whenever I update my data? I have used nl2br in this one. and how will my inputted date still show up whenever I hit my update button? TYVM.
Below are excerpts from my code
index
<div class="col-sm-2">
<input type="datetime-local" name="date_submitted" id="date_submitted" class="form-control" placeholder="Date Submitted" style="width: 120%;"/>
</div>
<div class="col-sm-3">
<textarea name="remarks" id="remarks" class="form-control" placeholder="Remarks" rows="2" style="margin-left:13%;"></textarea>
</div>
<div class="col-sm-2">
<input type="hidden" name="id" id="docu_id" />
<button class="button add" name="action" id="action" style="margin-left: 16%;">Add</button>
</div>
<br><br>
script
<script>
$(document).ready(function(){
fetchDocu();
function fetchDocu()
{
var action = "select";
$.ajax({
url: "select.php",
method: "POST",
data: {action:action},
success: function(data){
$('#code').val('');
$('#doc_kind').val('');
$('#date_submitted').val('');
$('#remarks').val('');
$('#action').text("Add");
$('#result').html(data);
}
});
}
$('#action').click(function(){
var docCode = $('#code').val();
var docKind = $('#doc_kind').val();
var dateSubmitted = $('#date_submitted').val();
var docRemarks = $('#remarks').val();
var id = $('#docu_id').val();
var action = $('#action').text();
if(docCode != '' && docKind != '' && dateSubmitted != '')
{
$.ajax({
url : "action.php",
method:"POST",
data:{docCode:docCode, docKind:docKind, dateSubmitted:dateSubmitted, docRemarks:docRemarks, id:id, action:action},
success:function(data){
alert(data);
fetchDocu();
}
});
}
else {
alert("All Fields are Required");
}
});
$(document).on('click','.update', function(){
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {id:id},
dataType: "json",
success:function(data){
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.docRemarks);
}
})
});
action.php
if($_POST["action"] == "Save")
{
$code = mysqli_real_escape_string($connect, $_POST["docCode"]);
$doc_kind = mysqli_real_escape_string($connect, $_POST["docKind"]);
$date_submitted = mysqli_real_escape_string($connect, $_POST["dateSubmitted"]);
$remarks = mysqli_real_escape_string($connect, $_POST["docRemarks"]);
$procedure = "
CREATE PROCEDURE updateDocu(IN docu_id int(11), docCode varchar(20), docKind varchar(150), dateSubmitted varchar(150), docRemarks varchar(150))
BEGIN
UPDATE officeSecTB SET code=docCode, doc_kind=docKind, date_submitted=dateSubmitted, remarks=docRemarks
WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL updateDocu('".$_POST["id"]."', '".$code."', '".$doc_kind."','".$date_submitted."', '".$remarks."')";
mysqli_query($connect, $query);
echo 'Data Updated';
}
}
}
and this is how I display the output
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tbody>
<tr>
<td>'.$row["code"].'</td>
<td>'.$row["doc_kind"].'</td>
<td>'.date('d M Y - H:i A', strtotime($row['date_submitted'])).'</td>
<td>'.nl2br($row["remarks"]).'</td>
<div class="row">
<td>
<div class="col-sm-6">
<button name="update" id="'.$row["id"].'" class="button update btn-xs">Update</button>
</div>
<div class="col-sm-6">
<button name="delete" id="'.$row["id"].'" class="button delete btn-xs">Delete</button>
</div>
</td>
</div>
</tr>
</tbody>
';
}
}
Sorry for the long post. Thank you in advance.
fetch.php
<?php
$connect = mysqli_connect("localhost","root", "", "ustjhsdts");
if(isset($_POST["id"]))
{
$output = array();
$procedure = "
CREATE PROCEDURE whereDocu(IN docu_id int(11))
BEGIN
SELECT * FROM officesectb WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL whereDocu(".$_POST["id"].")";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output['code'] = $row["code"];
$output['doc_kind'] = $row["doc_kind"];
$output['date_submitted'] = $row['date_submitted'];
$output['remarks'] = nl2br($row["remarks"]);
}
echo json_encode($output);
}
}
}
?>

Related

Following is a dynamic form code which can insert data by adding multiple inputs from user in row but I want it in column. How do I do it?

I downloaded the following code from internet. This code will add extra inputs from the user but it will create a new row in the database. I want this to be inserted in different columns of a row. How do I do it?
I have created fields for insertion in the Column.
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name"
class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add
More</button>
</td></tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info"
value="Submit" />
</form>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
And this is the name.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO tbl_name(namec) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
mysqli_query($connect, $sql);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>
As per your comments, I am assuming that there will be 4 names max. You can do the work as below:-
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
$db_col_names = array('namea','nameb','namec','named');
$names = array();
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i]) != '')
{
$names[] = mysqli_real_escape_string($connect, $_POST["name"][$i]); //get all the values from from in an array
}
}
$names = implode("','", $names); //make all the values as string to pass in insert query
$db_col_names = array_slice($db_col_names, 0, $number); //slice the DB columns to the names length entered
$db_col_names = implode("`,`", $db_col_names ); //make all the values as string to pass in insert query
$sql = "INSERT INTO tbl_name(`".$db_col_names."`) VALUES('".$names."')";
mysqli_query($connect, $sql);
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>
Hope this will do the work which you need. If any more modifications needed or any issue, do let me know in comments

Jquery Delete Button

I want to delete some records by using jQuery, i don't know what the error is, i cannot delete records. when i click edit button the records, it seems to work fine and record can be modified, but when i click delete button it does not work. here is my code:
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM apps_countries ORDER BY country_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<title>How to Make Editable Select Box using jQuery with PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="jquery-editable-select.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-editable-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">How to Make Editable Select Box using jQuery with PHP</h2><br />
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form method="post" id="sample_form">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label>Select Country</label>
<select name="country" id="country" class="form-control">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="action" id="action" value="add" />
<input type="hidden" name="hidden_id" id="hidden_id" value="" />
<input type="hidden" name="hidden_id1" id="hidden_id1" value="" />
<input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
</div>
</form>
<br />
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('tbody').html(data);
}
});
}
$('#country').editableSelect();
$('#sample_form').on('submit', function(event){
event.preventDefault();
if($('#name').val() == '')
{
alert("Enter Name");
return false;
}
else if($('#country').val() == '')
{
alert("Select Country");
return false;
}
else
{
$.ajax({
url:"action.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
alert(data);
$('#sample_form')[0].reset();
$('#action').val("add");
$('#save').val('Save');
fetch_data();
}
});
}
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("edit");
$('#save').val('Edit');
}
});
});
$(document).on('click', '.Delete', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});
});
</script>
fetch.php
<?php
include('database_connection.php');
$query = "SELECT * FROM sample_data ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["country"].'</td>
<td><button type="button" name="edit" class="btn btn-primary btn-xs edit" id="'.$row["id"].'">Edit</button></td>
<td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="3" align="center">Data not found</td>
</tr>
';
}
echo $output;
?>
action.php
<?php
include('database_connection.php');
if(isset($_POST["action"]))
{
if($_POST["action"] == "add")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"]
);
$query = "
INSERT INTO sample_data (name, country)
VALUES (:name, :country)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Inserted';
}
}
if($_POST["action"] == 'fetch_single')
{
$query = "SELECT * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['name'] = $row["name"];
$output['country'] = $row["country"];
}
echo json_encode($output);
}
if($_POST["action"] == "edit")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id"]
);
$query = "
UPDATE sample_data
SET name = :name, country = :country
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Updated';
}
}
if($_POST["action"] == "delete")
{
$data = array(
':name'=> $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id1"]);
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
}
}
?>
database_connection.php
<?php $connect = new PDO("mysql:host=localhost;dbname=sampl1", "root", ""); ?>
instead of button you can give tag like this
Delete
and featch id using $_REQUEST['id']
<?php
$id =$_REQUEST['id'];
// sending query
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
?>
I think your error could be here in this piece of code here.
Sometimes JQuery can be case sensitive.
Change this:
$(document).on('click', '.Delete', function(){
to this:
$(document).on('click', '.delete', function(){
At:
$(document).on('click', '.Delete', function(){ <-- CHANGE THIS LINE HERE AND LEMME KNOW IF IT WORKS
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});

Form echoed with PHP not submitting using ajax

I have a form that is echoed out from the database, but the issue is that when I try to submit, only the first echoed form submits and the rest doesn't. Below is my code.
editquestion.phh
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
echo '<form action="updatequestion.php" method="post" enctype="multipart/form-data">
<tr>
<td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>
<td><input type="text" name="question" id="question" value="'.$question.'"></td>
<td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>
<td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>
<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
</tr>
</form>';
}
?>
</tbody>
</table>
qupdate.js
$(document).ready(function() {
$('.qupdate').click(function() {
question = $('#question').val();
answer = $('#answer').val();
keywords = $('#keywords').val();
id = $('#cid').val();
$.ajax({
type: "POST",
url: "updatequestion.php",
data: "cid="+id+"&question="+question+"&answer="+answer+"&keywords="+keywords,
success: function(html){
if(html = "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
alert("not successful");
}
},
beforeSend: function(){
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
Just added the code for updatequestion.php.
<?php
session_start();
require_once("db.php");
$db = new MyDB();
if (isset($_POST['question']) || isset($_POST['answer']) || isset($_POST['cid']))
{
$id = strip_tags(#$_POST['cid']);
$cname = strip_tags(#$_POST['question']);
$cunit = strip_tags(#$_POST['answer']);
$keywords = strip_tags(#$_POST['keywords']);
if (empty($cname) || empty($cunit))
{
echo "fill";
}
else
{
$sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
$sql->bindParam(1, $cname, SQLITE3_TEXT);
$sql->bindParam(2, $cunit, SQLITE3_TEXT);
$sql->bindParam(3, $keywords, SQLITE3_TEXT);
$sql->bindParam(4, $id, SQLITE3_INTEGER);
$result = $sql->execute();
if ($result)
{
echo "true";
}
else
{
echo "false";
}
}
}
?>
But the ajax seems to only work for the first echoed data and doesn't seem to submit the rest. How do I solve this?
Thanks in advance.
Add class dynamic-form to form tag and remove id from all fields:
echo '<form class="dynamic-form" action="updatequestion.php" method="post" enctype="multipart/form-data">
<tr>
<td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>
<td><input type="text" name="question" value="'.$question.'"></td>
<td><input type="text" name="answer" value="'.$answer.'"></td>
<td><input type="text" name="keywords" value="'.$keywords.'"></td>
<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
</tr>
</form>';
Update in JS
$(document).ready(function () {
$('.dynamic-form').on('submit', function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "updatequestion.php",
data: formdata,
success: function (html) {
//success
}
});
return false;
});
});
Here is solution of your problem :-
$('.qupdate').click(function() {
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var id = $(this).closest("form").find('input[name=cid]').val();
});
It seems everyone here gave you almost the same answer, but it does not entirely satisfy your problem.
To give you the simplest answers:
What you are doing is bad practice by principle, because you should
not echo "forms"
Each form on the page has the same information
besides the inputs, which is wrong.
The correct solution:
Start using ajax post only for this purpose
Don't use FORM, instead just create a div for each question and have
the inputs there with the question id
Use a modal to edit the questions, that way when you close the
modal you reset the inputs in the modal, giving you the ability to
edit again a question and save it.
The solution you want right now:
editquestion.php
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
echo '<tr>';
echo '<td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>';
echo '<td><input type="text" name="question" id="question" value="'.$question.'"></td>';
echo '<td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>';
echo '<td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>';
echo '<td><input type="button" name="qupdate" class="qupdate" value="Update" onclick="doEdit('.$quiz_id.');"></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Question</h4>
</div>
<div class="modal-body">
<p>Edit your question:</p>
<p><input type="hidden" id="question_id" id="question_id" value=""></p>
<p><input type="text" id="question_text" value=""></p>
<p><input type="text" id="question_answer" value=""></p>
<p><input type="text" id="question_keywords" value=""></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="doupdate" class="btn btn-default">Update Question</button>
</div>
</div>
</div>
</div>
qupdate.js:
<script>
$(document).ready(function() {
function doEdit(question_id) {
/** POPULATE THE MODAL WITH THE QUESTION DATA **/
$.ajax({
type: "POST",
url: "getquestiondata.php", /** create this file, and return the question data from the database based on the "cid" **/
data: "cid="+question_id+",
success: function(response){
$('#question_id').val(response.cid);
$('#question_text').val(response.text);
$('#question_answer').val(response.answer);
$('#question_keywords').val(response.keywords);
}
});
}
/** DO THE ACTUAL UPDATE **/
$('#doupdate').click(function() {
var question_id = $('#question_id').val();
var question_text = $('#question_text').val();
var question_answer = $('#question_answer').val(),
var question_keywords = $('#question_keywords').val(),
$.ajax({
type: "POST",
url: "updatequestion.php",
data: "cid="+question_id+"&question="+question_text+"&answer="+question_answer+"&keywords="+question_keywords,
success: function(html){
if(html = "true")
{
$('.qupdate').css("opacity", "1");
$('#myModal').modal('toggle');
// Reset the modal inputs
$('#question_id').val("");
$('#question_text').val("");
$('#question_answer').val("");
$('#question_keywords').val("");
}
else
{
alert("not successful");
}
},
beforeSend: function(){
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
</script>
This code is untested, as I do not have your database or any information about the questions you store, however I am 90% positive that if you use this method it will work for you better than any other answer.
If I made some small typo or mistake, the code is very easy to edit and fix it.
FINAL NOTE: "updatequestion.php" is not the problem here, was never the problem.
Good luck!
As was mentioned by other people ID should be unique on the page.
In your case you can get whole form and serialize it's data:
$(document).ready(function() {
$('.qupdate').click(function() {
// Clicked $('.qupdate') is now $(this)
// But we should define $this variable if we want to be able to use it in callbacks.
// This is more efficient way instead of searching for $('.qupdate') in DOM again and again.
// Unless you want to set CSS for ALL .qupdate buttons in ALL forms.
var $this = $(this);
$.ajax({
type: "POST",
url: "updatequestion.php",
// find closest to .qupdate form and serialize it's data
data: $this.closest('form').serialize(),
success: function(html) {
// use double (or even tripple) equals operator if you want to compare, otherwise you'll just set html as "true"
// and it'll be always successful
if(html == "true") {
// We use $this variable here which we've defined earlier, and which, as we remember,
// stands for clicked $('.qupdate') button
$this.css("opacity", "1");
} else {
alert("not successful");
}
},
beforeSend: function() {
// We use $this variable here which we've defined earlier, and which, as we remember,
// stands for clicked $('.qupdate') button
$this.css("opacity", "0.5");
}
});
return false;
});
});
Update
Perhaps you send in response not exactly "true" or "false"?
In order to be sure that you don't send back any extra characters you should call exit after echo:
if ($result)
{
echo "true";
exit;
}
else
{
echo "false";
exit;
}
If you aren't sure you can simply remove this html check from JS since it never worked actually in your example:
// remove this if-else block
if(html = "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
alert("not successful");
}
You can also check what you send and what you get using browser developer tools. For example in chrome press F12 and in the opened panel select Network tab. Now click button in any form and you'll see that new request was sent. Wait for it to complete - Status column should receive some number (200 if everything was ok). Now you can click on this request and see details. There is even video example =) https://www.youtube.com/watch?v=WOQDrGrd9H8
I try to help using Sanjay Kumar answer since you want to save per row
editquestion.php
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
// assuming your database already connected here
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
// enctype="multipart/form-data" is used if the form contains a file upload, and echo per line for clarity
echo '<form action="updatequestion.php" method="post">';
echo '<tr>';
echo '<td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>';
echo '<td><input type="text" name="question" value="'.$question.'"></td>';
echo '<td><input type="text" name="answer" value="'.$answer.'"></td>';
echo '<td><input type="text" name="keywords" value="'.$keywords.'"></td>';
echo '<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>';
echo '</tr>';
echo '</form>';
}
?>
</tbody>
</table>
qupdate.js
// assuming you already loaded jquery library
$(document).ready(function()
{
$('.qupdate').click(function()
{
var id = $(this).closest("form").find('input[name=cid]').val();
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var postData = {'cid' : id, 'question' : question, 'answer' : answer, 'keywords' : keywords};
$.ajax(
{
type: "POST",
url: "updatequestion.php",
data: postData,
success: function(response)
{
// note the '==' operator
if(response == "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
console.log(response);
alert("not successful");
}
},
error: function(e)
{
console.log(e);
},
beforeSend: function()
{
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
updatequestion.php
<?php
session_start();
require_once("db.php");
$db = new MyDB();
if(isset($_POST['cid']) && isset($_POST['question']) && isset($_POST['answer']) && isset($_POST['keywords']))
{
$id = filter_input(INPUT_POST, 'cid', FILTER_SANITIZE_STRING);
$cname = filter_input(INPUT_POST, 'question', FILTER_SANITIZE_STRING)
$cunit = filter_input(INPUT_POST, 'answer', FILTER_SANITIZE_STRING)
$keywords = filter_input(INPUT_POST, 'keywords', FILTER_SANITIZE_STRING)
if($id == '' || $cname == '' || $cunit == '' || $keywords == '')
{
echo "one or more parameter is empty";
}
else
{
$sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
$sql->bindParam(1, $cname, SQLITE3_TEXT);
$sql->bindParam(2, $cunit, SQLITE3_TEXT);
$sql->bindParam(3, $keywords, SQLITE3_TEXT);
$sql->bindParam(4, $id, SQLITE3_INTEGER);
$result = $sql->execute();
if ($result)
{
echo "true";
}
else
{
echo "false";
}
}
}
else
{
echo "wrong parameter";
}
?>
I add some comment in the code.
You can inspect element and check in console tab for additional message if something not working, and i add filter input function for some security and change the comparison for empty variable.
I hope this give you some idea.
You can use in some other way may be it works
$(document).on('click','.qupdate',function() {
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var id = $(this).closest("form").find('input[name=cid]').val();
});
//or
jQuery('body').on('click', '.qupdate', function (){
var form = $(this).closest("form");
var forminput = form.serialize();
});

How to insert knockout generated JSON data in the mySql table?

I have a simple form that generates a JSON format of the 'brand name' input box. I've used knockout.js to generate the JSON from the form. Now, how can give this generated data to php action file to insert this JSON data in my mySql table named 'b_names' in the field 'brand_name' using php?
This is my form:
<button data-bind='click: addBrandName'>Add a drug</button>
<form action="php/action.php">
<table data-bind="foreach: brandNames">
<tbody >
<td>
<label>Brand name</label>
<input type="text" data-bind='value: brandName'>
</td>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
<p>
<button data-bind='click: save, enable: brandNames().length > 0'>Save to JSON</button>
</p>
<div>
<textarea data-bind='value: lastSavedJson' rows='10' cols='33'>
</textarea>
</div>
This is the script:
<script>
$( document ).ready(function() {
var initialData = [
];
var brandNamesModel = function(brandNames) {
var self = this;
self.brandNames = ko.observableArray(ko.utils.arrayMap(brandNames, function(drug) {
return {
brandName: drug.brandName };
}));
self.addBrandName = function() {
self.brandNames.push({
brandName: ""
});
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.brandNames), null, 2));
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new brandNamesModel(initialData));
});
</script>
I was trying this php action and surely it's not working.
$dbCon = mysqli_connect(localhost, $user, $password, $database)
or die ("error connecting database");
echo "Connected";
$data = file_get_contents($lastSavedJson);
$arrat = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO b_name(brand_name) VALUES('".$row["brandName"]."')";
mysqli_query($bdCon, $sql);
};
I'm trying to understand it so, any help would be appreciated.
Without the php here is the working fiddle of the form-
fiddle
Kindly try ajax call like in this way
$.ajax({
url: "your api url",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function(data){
console.log(data);
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
In your php you should check data is coming or not in php file like below & on your browser console. Check data is coming that you sent in console.
print_r($_POST['data']);
I've got the best help from the blog of Wern Ancheta. It is a great article and he explains all the codes there.
Here is his version of how he does the job that I've been looking for:
The html and knockout code:
<div class="container" data-bind="load: loadData()">
<div class="new_student">
<input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus"/>
<input type="text" class="age" placeholder="age" data-bind="value: person_age"/>
<button data-bind="click: createPerson">Create</button>
</div>
<table data-bind="visible: people().length > 0" class="students">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Remove</th>
<th>Update</th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<span data-bind="text: name, click: nameUpdating, visible: !nameUpdate()"></span>
<input type="text" class="name" data-bind="value: name, visible: nameUpdate, hasfocus: nameUpdate">
</td>
<td>
<span data-bind="text: age, click: ageUpdating, visible: !ageUpdate()"></span>
<input type="text" class="age" data-bind="value: age, visible: ageUpdate, hasfocus: ageUpdate">
</td>
<td>remove</td>
<td>update</td>
</tr>
</tbody>
</table>
<button data-bind="click: echoPerson">echo</button>
</div>
<script>
var personModel = function(id, name, age){
var self = this;
this.id = ko.observable(id);
this.name = ko.observable(name);
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false);
this.ageUpdate = ko.observable(false);
this.nameUpdating = function(){
self.nameUpdate(true);
};
this.ageUpdating = function(){
self.ageUpdate(true);
};
};
var model = function(){
var self = this;
this.person_name = ko.observable("");
this.person_age = ko.observable("");
this.people = ko.observableArray([]);
this.person_name_focus = ko.observable(true);
this.createPerson = function(){
if(self.validatePerson()){
var person = {'name' : this.person_name(), 'age' : this.person_age()};
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){
console.log(this);
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name("");
self.person_age("");
}
}
);
}else{
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
var id = person.id();
var name = person.name();
var age = person.age();
var student = {'id' : id, 'name' : name, 'age' : age};
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
this.loadData = function(){
//fetch existing data from database
$.ajax({
url : 'refresher_save.php',
dataType: 'json',
success: function(data){
for(var x in data){
var id = data[x]['id']
var name = data[x]['name'];
var age = data[x]['age'];
self.people.push(new personModel(id, name, age));
}
}
});
/*
note: nothing would actually show up in the success function if the
data that was returned from the server isn't a json string
*/
};
this.echoPerson = function(){
console.log(ko.toJS(self.people()));
};
};
ko.applyBindings(new model());
</script>
The server side php to connect, insert, update and delete data is:
<?php
$db = new MySqli('localhost', 'ashonko', '', 'tutorials');
$action = (!empty($_POST['action'])) ? $_POST['action'] : '';
$student = (!empty($_POST['student'])) ? $_POST['student'] : '';
if(!empty($student)){
$name = $student['name'];
$age = $student['age'];
}
switch($action){
case 'insert':
$db->query("INSERT INTO students SET name = '$name', age = '$age'");
echo $db->insert_id; //last insert id
break;
case 'update':
$id = $student['id'];
$db->query("UPDATE students SET name = '$name', age = '$age' WHERE id = '$id'");
break;
case 'delete':
$id = $_POST['student_id'];
$db->query("UPDATE students SET status = 0 WHERE id = '$id'");
break;
default:
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
$name_update = false;
$age_update = false;
$name_focus = false;
$age_focus = false;
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
'nameUpdate' => $name_update, 'ageUpdate' => $age_update,
'nameHasFocus' => $name_focus, 'ageHasFocus' => $age_focus
);
}
echo json_encode($students_r);
break;
}
?>

not able to carry the form values through post method

There is a form where the user enters a number and according to the condition applied on the number, a list of addresses are displayed. I would like to store the data that is returned through AJAX. The code on the page that has a form:
index.php
<script>
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: 'number='+number,
cache: false,
}).done(function(html) {
$('#results').html(html);
});
});
});
<script>
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit">Submit</button>
</form>
code on t_fetchaddr.php page
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
code on insert_temp.php page
$old_address = mysqli_real_escape_string($con, $_POST['old_address']);
echo $old_address;
Everything is working fine until displaying of the address through number, but when I submit the form it is not going to the back end. I tried to echo $old_address but got nothing.
other input values in index page inside the form are going to backend but value that is being fetched from t_fetchaddr.php page is not getting carried, Can anyone please tell where I went wrong
Try this and watch your console :
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number:number},
cache: false,
success : function(html) {
$('#results').html(html);
},
error : function(err){
console.log(err);
}
});
});
});
<script>
$(document).ready(function()
{
$("#phone").keyup(function()
{
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number :number}, //modified
cache: false,
success:function(html)
{
$('#results').html(html);
}
});
});
});
</script>//Missing closing
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit" >Submit</button>
</form>
and in php
$val = $_POST['phoneno'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
Note:
Missing closing tag </script>
And this line changed data: 'number='+number,
just try this code on fetchaddr.php
i have just removed the in between php tags.
<?
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0) {
echo '<div class="span6" >
<div class="span3">';
while($row2 = mysqli_fetch_assoc($result2))
{
echo '<input type="radio" name="old_address" value="'.$row2['address'].'" >'.$row2['address'].'<br>';
}
echo '</div>
</div>';
} ?>
hopefully this will solve your problem.

Categories