I am making a quiz app backend module. I am trying to edit question and answers, how can I edit Questions and the answers of that related question will show?
I have two tables questions
and answers
table.
Question table structure
id
| question
Answers table structure
id
| answer
| question_id
So question
table must be connected to question_id
to fetched it answers.
Right now I have this bug, where if I click any Questions I want to edit shows all the answers even that particular answer is not related to the question.
Bug or Problem of the app, please see
This Controller will call the model
public function editPost(){
$result = $this->post_model->showEditPost();
echo json_encode($result);
}
This Model queries it to show data.
public function showEditPost(){
// Show answers
$id = $this->input->get('id');
$this->db->select('*');
$this->db->from('answers');
$this->db->join('questions', 'answers.question_id = questions.id');
$this->db->where('questions.id', $id);
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
Show Edit Post function ajax script - this script shows the modal data
function showEditPost(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>posts/editPost',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<input type="text" value="'+data[i].answer+'" class="form-control" /><hr>';
}
$('#showEdit').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
This code triggers the Ajax
<div class="modal fade-scale" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<div class="card">
<div class="card-header">
<h4>Update Answers</h4>
</div>
<div class="card-body">
<form id="myForm">
<input type="hidden" name="answer" id="answer" class="form-control" />
<div id="showEdit"></div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="btnClose" class="btn btn-default">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Update</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
To display modal
//edit
$('#showdata').on('click', '.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Question');
$('#myForm').attr('action', '<?php echo base_url() ?>posts/updatePost');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>posts/editPost',
data: {id: id},
async: false,
dataType: 'json',
success: function(data){
//$('input#question').val(data.question);
$('input#answer').val(data.answer);
},
error: function(){
alert('Could not Edit Data');
}
});
});