Display data from database into existing textbox when click submit button - javascript

I have a problem. I want to display the data from database in the existing textbox but unfortunately, it does not display the result. My if else loop is not working. I don't want to display the textbox only if the button is click. I want the result display inside the existing textbox after the search button click.
here is my code html code:
<div class="row">
<div class="column middle2" style="background-color:transparent">
<div class="container"><br><br>
<div class="row">
<div class="col-01">
<label for="icno"><b>IC No :</b></label>
</div>
<div class="col-02">
<form action="" method = "POST">
<div class="input-group">
<input type="text" name="icpayer" value = "<?php if(isset($_POST['icpayer'])){echo $_POST['icpayer'];} ?>" class="form-control bg-light border-0 small" >
<div class="input-group-append">
<button type="button" id = "searchValue" class="btn btn-primary">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-01">
<label for="name"><b>Payer Name :</b></label>
</div>
<div class="col-02">
<input type="text" id="payername" name="payername" >
</div>
</div>
</div>
</div>
</div>
here is my javascript code:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
here is my php code:
<?php
if(isset($_POST['icpayer'])){
$searchValue = $_POST['icpayer'];
$query="SELECT * FROM ptregistration WHERE patientic = '$searchValue'";
$result = mysqli_query($con, $query) or die(mysqli_error($con,$query));
while($row = mysqli_fetch_array($result)){
echo $row['patientname'];
}
}else{
echo "No Record Found";
} ?>
my problem is when I click the search button, the result display "No Record Found" even there is similar data in the database. please help me as I am a beginner.

You should modify the ajax request to send the icpayer parameter. I do not use jQuery so I'm sure a better jQuery method exists but you can do so like this:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
data:{
icpayer:document.querySelector('input[name="icpayer"]').value
},
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
The PHP was exposing your database to SQL injection (potentially) so you should use Prepared Statements
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['icpayer'] ) ){
include($_SERVER['DOCUMENT_ROOT'].'/mhcsys/include/config.php');
$icpayer=filter_input( INPUT_POST, 'icpayer', FILTER_SANITIZE_STRING );
$sql='select `patientname` from `ptregistration` where `patientic`=?';
$stmt=$con->prepare($sql);
$stmt->bind_param('s',$icpayer);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows();
if( $rows > 0 ){
$stmt->bind_result( $patientname );
while( $stmt->fetch() )echo $patientname;
}else{
echo 'No Record Found';
}
}
?>

Related

select specific element jquery inside php foreach loop

I have foreach loop in php on front page for getting images and description of the image, inside foreach loop I have form, form is use for sending comment, this is front page..
<?php foreach ($photo as $p) : ?>
<div class="photo-box">
<div class="galP photo-wrapper" >
<div data-fungal="<?php echo $p->id; ?>" class='galFun-get_photo'>
<img src="<?php echo $p->thumb; ?>" class='image'>
</div>
</div>
<div class='inline-desc'>
<a href="/gallery/user.php?id=<?php echo $p->userId; ?>">
<?php echo $p->username; ?>
</a>
</div>
<form method="POST" action="" class="form-inline comment-form galForm">
<div class="form-inline">
<input type="hidden" class='photoId form-control' name="photoId" value="<?php echo $p->id; ?>" >
<input type="hidden" class='userId form-control' name="userId" value="<?php echo $session->userId; ?>" >
<textarea cols="30" rows="3" class='comment fun-gal-textarea' name="comment" placeholder="Leave your comment"></textarea>
<button type='button' name='send' class='sendComment'>SEND</button>
</div>
</form>
<div class='new-comm'></div>
<div class='comments-gal' id='comments'>
<div data-id='<?php echo $p->id; ?>' class='getComment'>
<span>View comments</span>
</div>
</div>
</div>
Using ajax I want to send userId,photoId and comment after clicking the button that has class sendComment. When I send comment on the first image everything is ok but when I try to send comment for some other image it wont work. I can't select that specific input and textarea for geting the right value .This is my jquery
$('body').on('click','.sendComment',function(){
var selector = $(this);
var userId = selector.siblings($('.userId'));
var photoId = selector.siblings($('.photoId'));
var c = selector.siblings($('.comment'));
var comment = $.trim(c.val());
if (comment == "" || comment.length === 0) {
return false;
};
$('#no-comments').remove();
$.ajax({
url: '/testComment.php',
type: 'POST',
data: {comment:comment,userId:userId,photoId:photoId}
}).done(function(result) {
...
}
})
});
Also, I have tried in every possible way to get the right value from the form without success..
This line
var userId = selector.siblings($('.userId'));
will be unlikely to get the correct input as, according to https://api.jquery.com/siblings/
.siblings( [selector ] )
selector
A string containing a selector expression to match elements against.
so this would need to be :
var userId = selector.siblings('.userId');
at that point you also need to get the actual value from the input, giving:
var userId = selector.siblings('.userId').val();
var photoId = selector.siblings('.photoId').val();
var c = selector.siblings('.comment');
and the rest of the code as-is.

To display data in the fields in the modal retrieved from the mysql database

Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});

j query updating div of drop-down after inserting data

I have a drop down which i am filling from database (ss and source attached)
<div id="divmedium">
<label>Medium:</label> <a data-toggle="modal" role="button" href="#medium_m">[Add New Medium]</a>
<select data-placeholder="Select Medium" class="select-full" tabindex="2" id="media" name="media">
<option value=""></option>
<?php
$quee = 'SELECT `media_id` , `mediatype` FROM `media` WHERE `bus_id_fk` = "'. $_SESSION['bus_id_fk'].'" order by `mediatype` asc';
$rs=$DBH->query($quee);
while($row = $rs->fetch_assoc()){
echo "<option value=$row[media_id]>$row[mediatype]</option>";
}
?>
</select>
</div>
if i click on [Add New Medium] , a model appears in which i can add value.
<div id="medium_m" class="modal fade" tabindex="-1" role="dialog">
<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"><i class="icon-paragraph-justify2"></i> Add New Medium </h4>
</div>
<!-- Form inside modal -->
<form action="#" role="form" id="med1">
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<label>First Medium</label>
<input type="text" name="fname" placeholder="Eugene" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
<button type="submit" id = "m_btn" class="btn btn-primary">Submit form</button>
</div>
</form>
</div>
</div>
click on submit form (AJAX)
$(document).ready(function(){
$('#med1').submit(function(){
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'addmedium.php',
//data: formData.serialize()
data: $(this).serialize()
})
.done(function(data){
$('#response').html(data);
if(data.status == 'success'){
$("#divmedium").html(data);
}else if(data.status == 'error'){
alert("Error on query!");
}
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
addmedium.php
<?php
session_start();
INCLUDE './config/databases.php';
header('Content-type: application/json');
$loc= $_POST['fname'];
$busid=$_SESSION['bus_id_fk'];
$sql = "INSERT INTO media (mediatype,bus_id_fk)VALUES ( '$loc','$busid' )";
//echo $sql;
if ($DBH->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $DBH->error;
}
$response_array['status'] = 'success';
echo json_encode($response_array);
exit;
?>
Now the problem is
data getting inserted in the database but i am unable to refresh the
div,
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
after clicking on Submit form , the div divmedium is disappearing.
Let me know what i am doing wrong.
I'll start from the end, if you won't mind.
after clicking on Submit form , the div divmedium is disappearing.
In your AJAX code $("#divmedium").html(data); you are replacing divmedium content with json_encode($response_array);
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
I don't see any code that should close it. Try to add data-dismiss="modal"
data getting inserted in the database but i am unable to refresh the div
Same stuff as in 3rd question, check this and edit your AJAX success callback.

Ajax loaded comment not working

My php file loops out each blog post in my database and also creates the comments section. The blogs post great. When I comment on the most recent blog post, the comment does not appear but it seems to add a line as the space expands, just does not include the comment. When I comment on the first post, it works great and exactly as expected. I can't figure out how to correct it. I thought it was a matter of add a .closest to the comment-block selector but that didn't seem to do the trick.
I appreciate any help or feedback!
PHP/HTML
<?php // retrive post
include('php/config.php');
include ('php/function.php');
dbConnect();
$blog_query = mysql_query(
'SELECT *
FROM Blog
ORDER BY DATE DESC');
$date = date_create($row['DATE']);
while($row = mysql_fetch_array($blog_query)): ?>
<div class="post">
<h2><?php echo $row['TITLE']?></h2>
<h3><?php echo date_format($date, 'l, F j, Y')?></h3>
<p><?php echo $row['CONTENT']?></p>
</div>
<h2>Comments.....</h2>
<div class="comment-block">
<?php // retrieve comments with post id
$comment_query = mysql_query(
"SELECT *
FROM Comments
WHERE BID = {$row['ID']}
ORDER BY CID DESC
LIMIT 15") or die(mysql_error());
while($comment = mysql_fetch_array($comment_query)):?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $comment['UNAME'] ?> <span>said....</span></h3>
<p><?php echo $comment['COMMENT']?></p>
</div>
</div>
<?php endwhile?>
</div>
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<div>
<input type="hidden" name="BID" value="<?php echo $row['ID']?>">
<label> <span>Display Name: *</span>
<input id="uname" type="text" tabindex="1" name="commentName" required />
</label>
</div>
<div>
<label> <span>Comment: *</span>
<textarea id="textarea" placeholder="Enter your comment here..." tabindex="2" name="commentMessage" required></textarea>
</label>
</div>
<div>
<input type="submit" id="submit" value="Submit Comment">
</div>
</form>
<?php endwhile?>
</div>
Jquery/Ajax:
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'php/ajaxcomment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
ajajcomment.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('config.php');
include('function.php');
dbConnect();
if (!empty($_POST['commentName']) AND !empty($_POST['commentMessage']) AND !empty($_POST ['BID'])) {
$name = mysql_real_escape_string($_POST['commentName']);
$comment = mysql_real_escape_string($_POST['commentMessage']);
$BID = mysql_real_escape_string($_POST['BID']);
mysql_query("
INSERT INTO Comments
(UNAME, BID, COMMENT)
VALUES('{$name}', '{$BID}', '{$comment}')");
}
?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo $comment ?></p>
</div>
</div>
<?php
dbConnect(0);
endif?>
What does "php/ajaxcomment.php" return when you post a comment? Pure HTML?
I'd make the "php/ajaxcomment.php" return JSON, for example:
<?php
/*
here you do what ever you do now,
Insert the new comment to database, etc
*/
// Then you return the inserted data:
$data = array(
'UNAME' => $username,
'COMMENT' => $comment,
);
header('Content-Type: application/json');
print json_encode( $data );
?>
..and change the ajax:
...
...
success: function(data){
var commentItem = $('<div/>').addClass('comment-item');
var commentPost = $('<div/>').addClass('comment-post');
var user = $('<h3/>').html( data.UNAME +'<span>said...</span>' );
var comment = $('<p/>').html( data.COMMENT );
commentItem.html( commentPost.html( user + comment ) ).hide().fadeIn(800);
$('.comment-block').append(commentItem);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
...
...

Send data from controller to pop up modal using bootstrap codeigniter

Hello I was going to make a forgot password function using modal bootstrap..
before I have made it without pop up modal.. I do know how to pass the data..
but now I don't know how to send data from controller to pop up modal..
Here is my code:
<div id="forgot-password" class="modal hide fade in" style="display: none; ">
<div class="modal-header" style="background-color:#f39c12; color:#fff;">
<h3 id="helpModalLabel"> Forgot Password</h3>
</div>
<div class="modal-body">
<form class="form-horizontal well" method="post" id="forgot_form" action="<?php echo base_url(); ?>forgotpassword/doforget">
<fieldset>
<legend></legend>
<div class="control-group">
<?php if( isset($info)): ?>
<div class="alert alert-block alert-success fade in" id="alert-message" >
<img src="<?php echo base_url("assets")?>/image/Done.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($info) ?>
</div>
<?php elseif( isset($error)): ?>
<div class="alert alert-block alert-error fade in" id="alert-message">
<img src="<?php echo base_url("assets")?>/img/icon/warning.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($error) ?>
</div>
<?php endif; ?>
<label for="Username" class="control-label span3" >Username</label>
<div class="controls">
<input class="span3" type="text" id="Username" name="Username" placeholder="Input the Registered Username" name="Username"/>
<span id="UsernamehelpText"></span>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Send Password" name="submitbtn"/>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
Close
</div>
</div>
Controller
public function forget()
{
if (isset($_GET['info'])) {
$data['info'] = $_GET['info'];
}
if (isset($_GET['error'])) {
$data['error'] = $_GET['error'];
}
$page_content["page_title"] = "";
$page_content["title"] = "Forgot Password";
$page_content["icon_title"] = "home";
$menu_params["sub_current_navigable"] = "";
$page_content["navmenu"] = $this->load->view("nav_menu", "", true);
$page_content["menu"] = $this->load->view("main_menu_login", $menu_params, true);
if(isset($data)){
$page_content["content"] = $this->load->view("forgotpassword",$data, true);
}else{
$page_content["content"] = $this->load->view("forgotpassword","", true);
}
$this->load->view("template/main_template", $page_content);
}
public function doforget()
{
$this->load->helper('url');
$username= $_POST['Username'];
$checkuser = $this->forgotpassword_model->getusername($username);
print_r($checkuser);
$getemail = $this->forgotpassword_model->getemail($username);
if(!empty($checkuser))
{
$user = $checkuser['0'];
$email = $getemail['0'];
if(!empty($email['email']))
{
$this->sendpassword($user,$email);
$info= "Password has been reset and has been sent to email id: ". $email['email'];
echo $info;
redirect('login/forget?info='.$info, 'refresh');
}else{
$error = "You don't have email, please contact your admin library ";
echo $error;
redirect('login/forget?error=' . $error, 'refresh');
}
}else
{
$error= "You have input wrong username ";
redirect('login/forget?error=' . $error, 'refresh');
echo $error;
}
}
Can someone help me to migrate this to pop up modal? do I need ajax?
I also want to send the error message to pop up modal..
now I'm using 'login/forget?error=' . $error, 'refresh')
Is it possible for me for still using this?
EDIT
to pass your data from Controller to bootstrap modal you need json. to do that try this:
in your controller
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $your_data_array ));
this code change your array data to JSON and then send it to whatever you call this method. with your AJAX call this method and in success get this data parse it with JSON.pars() method and put them to your modal.
In CodeIgniter, before using a model you need to load it. For example you write a model in model folder with name userAuth. Creating a model is as follows:
class UserAuth extends CI_Model{
//your methods
}
In your model you can have some method like forgetPass that will give you an array or data like:
public function forgetPass($dataArray){
//your Code
}
OR
public function forgetPass( $data1, $data2, $data3){
//your code
}
When you want to use your model in a controller method you can load it handily in your controller method or load it in controller constructor like this:
$this->load->model('userAuth');
When you need a method like that, according to the example given you can pass your data to it as:
$this->userAuth->forgetPass($data);
addition:
In CodeIgniter, we have in-built methods to get POST / GET data. They are easy to use and safer. You can use:
$variable = $this->input->post('your_input_name');
OR
$variable = $this->input->get('your_key');
Instead of $_GET['your_key'] or $_POST['your_input_name']

Categories

Resources