what to retrieve image from database using json ajax function in codeigniter - javascript

This is my first time of trying to retrieve image using ajax/json format, all other variable are displaying except the image because i dont know how integrate the syntax in ajax,
And when i open the inspect element on the browser the name of the image is showing and it saving into the image folder as well correctly
what i just need from u guys is help me display the image inside the form without function
Thanks in advance
This is my ajax function
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('person/ajax_edit/')?>/" + firstname,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="firstName"]').val(data.firstname);
$('[name="lastName"]').val(data.lastname);
$('[name="gender"]').val(data.gender);
$('[name="address"]').val(data.address);
$('[name="gender"]').val(data.gender);
$('[name="telephone"]').val(data.telephone);
$('[name="level"]').val(data.level);
$('name="image"').val(data.image)
$('[name="religion"]').val(data.religion);
$('[name="entrance"]').val(data.entrance);
$('[name="graduate"]').val(data.graduate);
$('[name="parents"]').val(data.parents);
$('[name="dob"]').datepicker('update',data.dob);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
This is controller
public function ajax_edit($firstname)
{
$data = $this->person->get_by_id($firstname);
$data->dob = ($data->dob == '0000-00-00') ? '' : $data->dob; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
This is my model
public function get_by_id($firstname)
{
/*
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
*/
$this->db->select("e.*,edu.*");
$this->db->from("student_details e");
$this->db->join("images edu", "edu.firstname = e.firstname", 'left');
$this->db->where('e.firstname', $firstname);
$result = $this->db->get();
return $result->row();
}
This is my view
<div class="form-group">
<label class="control-label col-md-3">Religion</label>
<div class="col-md-9">
<select name="religion" class="form-control">
<option value="">--Select Religion--</option>
<option value="Christain">Christain</option>
<option value="Muslim">Muslim</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">Image</label>
<div class="">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="assets/img/demoUpload.jpg" alt="" /></div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div align="center">
<span class="btn btn-file btn-primary"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" name="userfile" ></span>
Remove
<span class="help-block"></span>
</div>
</div>
</div>
</div>

public function DISPLAY() {
$abc = "";
$data = $this->Model1->display('users');
$abc .= "<table class='table table-condensed'><th>ID</th><th>Image</th><th>Name</th>
<th>Email</th><th>Mobile</th><th>Action</th>";
for ($q=0; $q<count($data); $q++){
$abc .= "<tr><td>".$data[$q]['ID']."</td><td>
**<img src='".base_url('uploads/USERS/'.$data[$q]['IMAGE'].'')."'".$data[$q]['IMAGE']." height='50' width='60'></td>**
<td>".$data[$q]['FNAME']." ".$data[$q]['LNAME']."</td>
<td>".$data[$q]['EMAIL']."</td>
<td>".$data[$q]['MOBILE']."</td>
<td><button id='EDIT' class= 'btn btn-primary fa fa-EDIT EDIT' value='".$data[$q]['ID']."' data-toggle='modal' data-target='#myModal'></button></td>
<td><button class='btn btn-danger fa fa-trash DELETE ' value='".$data[$q]['ID']."'data-toggle='modal' data-target='#myModal'></button></td>
</tr></table>";}
print_r($abc);
}}
$.ajax({
url:'<?php echo base_url('index.php/Adminc/DISPLAY/')?>',
success:function(display){
$(".table-condensed").html(display);
},
});

Related

Display data from database into existing textbox when click submit button

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';
}
}
?>

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Ajax file upload in PHP using javascript popup [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 3 years ago.
I am having problem with uploading file with JavaScript Popup. This is my first experience to upload file with such JavaScript popup. I don't know how to pass the input[type:file] to the ajax function and then send to the php file for uploading.
This is the button which calls the popup:
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadDocument">Upload Document</a>
<div class="modal fade" id="uploadDocument" role="dialog">
<div class="modal-dialog" style="top: 20%;">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="background-color: #367FA9">
<h4 class="modal-title" id="myModalLabel" style="color:white">Upload Document</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="padding-top: 20px; padding-right: 40px; padding-left: 40px;">
<!-- <img src="police/images/new.jpg" width="120px" height="100px"> -->
<p id="uploadMD"></p>
<form role="form" id="uploadForm" >
<div class="form-group">
<input type="hidden" name="" id="rowid" value="<?php echo $id; ?>">
</div>
<div class="form-group">
<label>Document Name</label>
<input type="text" name="" id="documentName" class="form-control">
</div>
<div class="form-group">
<label>Document</label>
<input type="file" class="form-control" placeholder="Please Select File" id="documentFile">
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary submitBtn block" style="background-color: #367FA9" onclick="uploadDocument()" style="width: 100%;">Upload Document</button>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The javascript code is as follows:
<script>
function uploadDocument(){
var rowid = $('#rowid').val();
var documentName = $('#documentName').val();
var documentFile = $('#documentFile').val();
if(documentName.trim() == '' ){
alert('Please write file name');
$('#documentName').focus();
return false;
}else if(documentFile.trim() == '' ){
alert('Please Select File');
$('#documentFile').focus();
return false;
}else {
$.ajax({
method:'POST',
url:'upload.php',
enctype: 'multipart/form-data',
data:'&rowid='+rowid+'&documentName='+documentName+'&documentFile='+documentFile,
success: function(result){
$('#uploadForm').trigger('reset');
if(result == '1'){
$('#uploadMD').html('<span style="color:green;">Your File is uploaded. Thank you</span>');
setTimeout(function(){ window.location.reload() }, 5000);
}
else{
$('#uploadMD').html('<span style="color:red;">Uploading Problem</span>').fadeIn().delay(5000).fadeOut();
}
}
});
}
}
</script>
and the upload.php file is here:
<?php
$rowid = $_POST['rowid'];
$documentName = $_POST['documentName'];
$file_name = $_FILES['documentFile']['name'];
$file_move = move_uploaded_file($file_tmp,"../uploads/ps/".$file_name);
include "../include/configs.php";
if ($file_move) {
$q2 = "UPDATE requests SET support_doc='$file_name' WHERE slug='$id'";
$query = mysqli_query($con, $q2);
if ($query) {
echo $success = 1;
}
}
?>
Thanks in advance.
Try formdata to pass in php file ajax call
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
Thanks

Simple Ajax form submit!? (Can't understand)

I will try to explain my code simple. Basicly I got 2 different files:
fun.php
class.fun.php
I want to post my forms with ajax, so it won't refresh page.
In class.fun.php I have got reportForm for each post.
<!-- REPORT MODAL -->
<div class="modal fade report_post_<?php echo $post['id'];?>" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<b><center><div class="modal-header">Report Post</div></center></b>
<form class="horiziontal-form" id="reportForm" action="../Pages/fun.php?action=reportPostForm" method="post">
<center><textarea name="report" style="width:80%; height:200px; margin-top:20px; resize:vertical;" placeholder="Please describe your Report!"></textarea></center>
<input type="hidden" name="addedby" class="form-control col-md-7 col-xs-12" value="<?php echo $myRow['id']; ?>" />
<input type="hidden" name="image_id" class="form-control col-md-7 col-xs-12" value="<?php echo $post['id']; ?>" />
<div class="modal-footer"> <input type="submit" name="submit" value="Submit Form" /></div>
</div>
</div>
</form>
</div>
<!-- END OF REPORT MODAL -->
And after form I got ajax function:
<script>
$("#reportForm").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});
</script>
When I click button submit I want to send form data to fun.php
This is how I receive data in fun.php
if(isset($_POST['reportPostForm'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
}
And send them to other function in class.fun.php
But at this moment nothing happens. I have been looping trought many
tutorials and can't understand how to make this work. Im newbie in
javascript. I have got working upvote/downvotes scripts where I pass only post_id and it works.
I have got script for upvote that works:
$("#upvote_<?php echo $post['id'];?>").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
$('#upvote_<?php echo $post['id'];?>').load(document.URL + ' #upvote_<?php echo $post['id'];?>');
$('#downvote_<?php echo $post['id'];?>').load(document.URL + ' #downvote_<?php echo $post['id'];?>');
$('#comment_<?php echo $post['id'];?>').load(document.URL + ' #comment_<?php echo $post['id'];?>');
$('#share_<?php echo $post['id'];?>').load(document.URL + ' #share_<?php echo $post['id'];?>');
$('#report_<?php echo $post['id'];?>').load(document.URL + ' #report_<?php echo $post['id'];?>');
$('#report_btn_<?php echo $post['id'];?>').load(document.URL + ' #report_btn_<?php echo $post['id'];?>');
document.getElementById("result-box").innerHTML = result;
}
});
});
On fun.php you are checking for $_post['reportPostForm'] but this is not sent via post on this ajax call. your firm doesn't have this inputime and that's why nothing is happening. Try if(isset($_POST['report'])
Change this:
if(isset($_POST['report'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
echo "Done";
}
Also add the <div id='server-results'></div> to your form so that you can show the resutls.
<div class="modal-dialog modal-lg">
<div class="modal-content">
<b>
<center>
<div class="modal-header">Report Post</div>
</center>
</b>
<form class="horiziontal-form" id="reportForm" action="../Pages/fun.php?action=reportPostForm" method="post">
<center>
<textarea name="report" style="width:80%; height:200px; margin-top:20px; resize:vertical;" placeholder="Please describe your Report!"></textarea>
</center>
<input type="hidden" name="addedby" class="form-control col-md-7 col-xs-12" value="<?php echo $myRow['id']; ?>" />
<input type="hidden" name="image_id" class="form-control col-md-7 col-xs-12" value="<?php echo $post['id']; ?>" />
<div class="modal-footer">
<input type="submit" name="submit" value="Submit Form" />
</div>
</div>
</div>
<div id='server-results'></div>
</form>
</div>
It is not very clear what is not working.
The file is correct.
Only problem is in fun.php as you do:
if(isset($_POST['reportPostForm'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
}
But you are sending $_POST['addedby'], $_POST['image_id'] and $_POST['report'].
The one you are checking $_POST['reportPostForm'] do not exists.
Try to do the if against one of the three values you are passing.

Show Multiple Value With Ajax

I have 2 db 'srtptr' and 'deskripsisrt' and I want to show them with modal bootstrap
I successfully show from 'srtptr' but I don't know how to show from 'deskripsisrt',..
this my db 'deskripsisrt'
+--------------+------------------+-----------+
| id_des | deskripsi | id_srt |
+--------------+------------------+-----------+
| 1 | Test 4 | 4 |
| 2 | Test 2 | 4 |
+--------------+------------------+-----------+
I want to show multiple values on my modal.
Modal script:
<div class="modal fade" id="myModals" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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="myModalLabel">Add User</h4>
</div>
<div class="modal-body" style="max-height: 600; overflow-y: scroll;">
<div class="alert alert-danger" role="alert" id="removeWarning">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Anda yakin ingin menghapus user ini
</div>
<br>
<form class="form-horizontal" id="formUser" method="post" target="blank">
<input type="hidden" class="form-control" id="type" name="type">
<input type="hidden" class="form-control" id="id_srt" name="id_srt">
<input id="desc" value="1" type="hidden" >
<span style="font-weight: bold">Kepada PT</span>
<div class="input-group">
<input type="text" class="form-control" name="tujuan_srt" id="tujuan_srt" value="" title="Tujuan Surat" placeholder="Tujuan Surat" maxlength="25" size="100">
</div>
</br>
<span style="font-weight: bold">Kepada Nama</span>
<div class="input-group">
<input type="text" class="form-control" name="kepada_srt" id="kepada_srt" value="" title="Tujuan Surat" placeholder="Tujuan Surat" maxlength="25" size="100">
</div>
</br>
<span style="font-weight: bold">Tanggal</span>
<div class="input-group">
<input type="text" name="tanggal" class="form-control" id="tanggal" value="<?php echo $fungsi->Tanggal('tgl').' '.$fungsi->Tanggal('blnL').' '.$fungsi->Tanggal('THN'); ?>" title="Tanggal Pembayaran" readonly="readonly" size="100">
</div>
</br>
<div class="col-md-6 konten "></br>
<span style="font-weight: bold">Deskripsi</span>
</div>
<div class="col-md-6 konten " style="Text-align: Right;"></br>
<button type="button" onclick="tambahDesc(); return false;" style="cursor:pointer; font-size:8pt; border-radius:2px; min-width:10px; border:0px; background:#4D4D4D; color:#FFFFFF; font-weight:bold;">Tambah Deskripsi</button>
</div>
<table border="1" style="width:30%" id="test">
<tr><td>deskripsi</td></tr>
**I WANT TO SHOW VALUE FROM DB 'deskripsisrt' HERE!!**
</table>
<div id="divDesc"> </div>
</br></br></br></br>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="btn1" class="btn btn-default" style="align:left">Cetak</button>
<button type="button" onClick="submitUser()" class="btn btn-default" data-dismiss="modal">Submit</button>
<button type="button" onClick="clearModals()" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
AJAX Code:
//Show Modal
function showModals( id_srt )
{
waitingDialog.show();
clearModals();
// For Execute Data (EDIT & DELETE)
if( id_srt )
{
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: {id_srt:id_srt,type:"get"},
success: function(res) {
waitingDialog.hide();
setModalData( res );
}
});
}
// FOR ADD Data
else
{
$("#myModals").modal("show");
$("#myModalLabel").html("New User");
$("#type").val("new");
waitingDialog.hide();
}
}
//Show Data On Modal For Edit
function setModalData( data )
{
$("#myModalLabel").html(data.id_srt);
$("#id_srt").val(data.id_srt);
$("#type").val("edit");
$("#tujuan_srt").val(data.tujuan_srt);
$("#kepada_srt").val(data.kepada_srt);
$("#tanggal").val(data.tanggal);
$("#myModals").modal("show");
}
//For Execute EDIT/DELETE/ADD NEW To DB
function submitUser()
{
var formData = $("#formUser").serialize();
waitingDialog.show();
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: formData,
success: function(data) {
dTable.ajax.reload(); // Automatic Reload Table Page
waitingDialog.hide();
}
});
}
$('#btn1').click(function()
{
$('#formUser').attr('action','setcetak.php');
$('#formUser').submit();
}
);
//Delete Data
function deleteUser( id_srt )
{
clearModals();
$.ajax({
type: "POST",
url: "crud.php",
dataType: 'json',
data: {id_srt:id_srt,type:"get"},
success: function(data) {
$("#removeWarning").show();
$("#myModalLabel").html("Delete User");
$("#id_srt").val(data.id_srt);
$("#type").val("delete");
$("#tujuan_srt").val(data.tujuan_srt).attr("disabled","true");
$("#kepada_srt").val(data.kepada_srt).attr("disabled","true");
$("#tanggal").val(data.tanggal).attr("disabled","true");
$("#myModals").modal("show");
waitingDialog.hide();
}
});
}
//Clear Modal
function clearModals()
{
$("#removeWarning").hide();
$("#tujuan_srt").val("").removeAttr( "disabled" );
$("#kepada_srt").val("").removeAttr( "disabled" );
$("#tanggal").val("").removeAttr( "disabled" );
}
// ADD Description Field
function tambahDesc() {
var desc = document.getElementById("desc").value;
var stre;
stre="<div id='srow" + desc + "'><div class='col-md-12 konten' style='Text-align: Right;'></br><a href='#' style=\"color:#EC090D; cursor:pointer; text-align: Right;\" onclick='hapusElemen(\"#srow" + desc + "\"); return false;'>hapus</a><div class='input-group'><textarea rows='6' cols='100' type='text' class='desce form-control' name='deskripsi[]' placeholder='deskripsi' size='100'></textarea></br></div></div></div>";
$("#divDesc").append(stre);
desc = (desc-1) + 1;
document.getElementById("desc").value = desc;
}
//Delete Description Field
function hapusElemen(desc) {
$(desc).remove();
}
$(function(id_srt) {
var data_table = "";
$.ajax({
type:"POST",
url: "crud.php",
dataType: "json",
data:{id_srt:id_srt,type:"getdes"},
success: function(data) {
for (var i =0; i<data.length; i++){
data_table +="<tr> <td> "+data[i].deskripsi+"</td></tr>";
}
$('#test').append(data_table);
}
});
});
Controller Code :
<?php
require 'config/action.php';
$fungsi = new Fungsi();
//Connection Database
$con = mysqli_connect("localhost","root","","kw");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
switch ($_POST['type']) {
//Tampilkan Data
case "get":
$SQL = mysqli_query($con, "SELECT * FROM srtptr WHERE id_srt='".$_POST['id_srt']."'");
$return = mysqli_fetch_array($SQL,MYSQLI_ASSOC);
echo json_encode($return);
break;
case "getdes": // NEW CODE This Show a table 'deskripsisrt'
$SQL =mysqli_query($con,"SELECT * FROM deskripsisrt WHERE id_srt = '".$_POST['id_srt']."'");
while ($return = mysqli_fetch_array($SQL,MYSQLI_ASSOC)) {
$rows[] = $return;
}
echo json_encode($rows);
break;
//Tambah Data
case "new":
$SQL = mysqli_query($con,
"INSERT INTO kwitansi SET
kwnum='".$_POST['kwnum']."',
tglkw='".$_POST['tglkw']."',
dari='".$_POST['dari']."',
penerima='".$_POST['penerima']."',
nominal='".$_POST['nominal']."',
pembayaran='".$_POST['pembayaran']."'
");
if($SQL){
echo json_encode("OK");
}
break;
//Edit Data
case "edit":
$SQL = mysqli_query($con,
"UPDATE srtptr SET
tujuan_srt='".$_POST['tujuan_srt']."',
kepada_srt='".$_POST['kepada_srt']."',
tanggal='".$_POST['tanggal']."'
WHERE id_srt='".$_POST['id_srt']."'
");
if($SQL){
echo json_encode("OK");
}
break;
//Hapus Data
case "delete":
$SQL = mysqli_query($con, "DELETE FROM srtptr WHERE id_srt='".$_POST['id_srt']."'");
if($SQL){
echo json_encode("OK");
}
break;
}
?>
I think this needs a loop on ajax but I don't know to make the loop ajax.
Assuming that the json coming from controller is like this
[
{"id_des":45,"deskripsi":"test","id_srt":2},
{"id_des":46,"deskripsi":"test1","id_srt":3},
{"id_des":47,"deskripsi":"test2","id_srt":4},
]
update your function of success like this
success: function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
console.log(k + " " +v);
});
});
}

Categories

Resources