Append content to div via jquery - php

My project is a kind of blog, with posts and comments area. I'm trying to make it async with jquery ajax. My problem is that when a new comment gets inserted asynchronously it appears in the div twice, and all the other comments disappear. If i refresh the page it looks fine.
VIEW:
<section id="comments_section_<?php echo $p1['post_id'];?>"> //THIS IS THE OUTPUT WHERE NEW COMMENTS WILL BE APPENDED
<?php
$data['comments'] = $this->model_mutamba->getComments($p1['post_id']);
if($data['comments'] != ""){ ?>
<div class="comments_container" id="comments_container_<?php echo $p1['post_id'];?>">
<?php foreach ($data['comments'] as $c){
$user_img3 = $this->model_mutamba->getUserPicId($c->aluno_id);
?>
<div>
<img style="height:32px;" src="<?php echo site_url();?>img/users/portfolio/<?php echo $user_img3;?>" alt="" class="align-left" />
<p>
<?php echo $this->model_mutamba->addSmilies($c->comment);?>
<br>
<span class="comments_date">
<?php
$c_date = explode('-', substr($c->comment_date,0,-8));
$date_num_word = monthNumToWords($c_date[1]);
echo substr($c->comment_date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0];?>
</span>
</p>
</div>
<?php } ?>
</div>
<?php } ?>
</section>
JS:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).html(response);
$(output).append(response);
}
});
}
}
CONTROLLER:
function insertNewComment(){
if($this->session->userdata('is_logged_in')){
$email= $this->session->userdata('email');
$comment= $this->FilterData($this->input->post('comment'));
$post_id= $this->FilterData($this->input->post('post_id'));
$this->load->model('model_mutamba');
if($this->model_mutamba->insertNewComment($email,$comment,$post_id)){
$this->load->model('model_user');
$count = $this->model_mutamba->countPostComments($post_id);
?>
<script>
var count = '<?php echo $count;?>';
var comments_count = '<?php echo "#comments_count_".$post_id;?>';
var content = "";
if(count == 1){
content = '<span class="comments_count">'+count+'</span> Comentário';
}else{
content = '<span class="comments_count">'+count+'</span> Comentários';
}
$(comments_count).html(content);
</script>
<?php
$this->load->model('model_user');
$user_img = $this->model_user->getUserPic($email);
echo '
<div>
<img style="height:32px;" src="'.site_url().'img/users/portfolio/'.$user_img.'" alt="" class="align-left" />
<p>
'.$this->model_mutamba->addSmilies($comment).'
<br>
<span class="comments_date">';
$date = date(date('Y-m-d H:i:s'));
$c_date = explode('-', substr($date,0,-8));
$date_num_word = monthNumToWords($date[1]);
echo substr($date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0].'
</span>
</p>
</div>';
}
}else{
redirect("inicio");
}
}
Will appreciate any help,
Thanks in advance

This is happening because in your AJAX success callback, you are adding response to the output TWICE - once with .html() and then again with .append().
.html(response) removes the previous HTML in your webpage, thats why you dont see other comments and it adds response to it.
With .append(response), it is adding response to the bottom of the div, that is the reason you are seeing the response twice!
Remove $(output).html(response) from the success callback and it will work fine.
So, your function needs to look like this:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).append(response);
}
});
}
}

function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
//$(output).html(response); //Comment this line or the line below it.
$(output).append(response);
}
});
}
}

<div id="appenddiv">
<h1>append</h1>
</div>
<script type="text/javacript">
$("#appenddiv").append('<b>hello world</b>');
</script>

Related

PHP and AJAX - like system - like the twitter system

I was making a 'like system' - like the twitter system - with PHP and AJAX. In a way that I can't understand, it applies to all buttons on the page when I press only one button. Please help.
enter image description here
index.php
<div id="rezbtn">
<span id="rezarea">
<button style="font-size:15px; float:left; <? if($sorus["soru_id"] == $rezs['soru_id'] && $user_id == $rezs['user_id']){ echo 'color:green;';}else{ echo ''; } ?>" class="btn rezle" id="rezle" type="button" title="<? echo $sorus["soru_id"]; ?>">
<span>#Rezle <? echo $rez["rez_id"]; ?></span>
</button>
</span>
</div>
ajax.php
if($rezuscount > 0)
{
echo "<span style='color:black;'>#Rezle ", $rezcount-1,"</span>";
}
else
{
echo "<span style='color:green;'>#Rezle ", $rezcount+1,"</span>";
}
like.js
$('.rezle').click(function(){
var soruid = $(this).attr("title");
$.ajax({
type:"POST",
url:"ajax.php",
data:{"soru":soruid},
success:function(e)
{
$('.rezle').html(e);
}
})
});
My codes are like this.
Your problem here is that you're referring to all elements with the class rezle and updating them all with the ajax html response:
$('.rezle').html(e);
try this:
$('.rezle').click(function(){
const rezle_button = this;
var soruid = $(this).attr("title");
$.ajax({
type:"POST",
url:"rezle.php",
data:{"soru":soruid},
success:function(e)
{
$(rezle_button).html(e);
}
})
});

How to get the output using ajax when the Double outputs displayed one for PHP Echo and another for Ajax request?

I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (#the bottom of index.php), and the Second output displayed through PHP ECHO (**#**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?
index.php
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
<div id="table_content"></div>
<?php
include ("db.php");
error_reporting(~E_NOTICE);
function ShowForm($AnswerCommentId) {
echo '<form id="myForm">';
echo '<input id="user" name="user" />';
echo '<textarea id="text" name="text"></textarea>';
echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
echo '<button type="button" OnClick=SendComment()>Comment</button>';
echo '</form>';
}
$query="SELECT * FROM `comm` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId'])) $AnswerId = $_REQUEST['AnswerId'];
else $AnswerId = 0;
$i=0;
while ($mytablerow = mysqli_fetch_row($result)){ $mytable[$i] = $mytablerow; $i++; }
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
foreach($treeArray as $item){
if ($item[1] == $pid){
echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);
echo sprintf('<p>%s</p>', $item[2]);
echo sprintf('<div>%s</div>', $item[3]);
if ($level<=2) echo sprintf('Reply', $item[0]);
if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
echo '</div><br/>';
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable,0,0);
?>
Comment
<div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
<div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){
$("#Link").click(function () {
$("#InnerDiv").remove();
$("#MainAnswerForm").slideToggle("normal");
return false;
});
});
</script>
</body>
Page.php
<?php
include ("db.php");
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];
if ($action=="add") $query= mysqli_query($conn,"INSERT into `comm` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())");
?>
Javas.js
function show_messages(){
$.ajax({
url: "index.php",
cache: false,
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "page.php",
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
show_messages();
}
});
return false;
}
OK I think its more simple than you think
while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using
<div id="table_content"></div>
<?php ?>
just wrap the <?php ?> inside the div
<div id="table_content">
<?php ?>
</div>
Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below
$(document).ready(function(){
$('#table_content').remove();
$('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
margin : 50px;
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>

Second select depending on first select using AJAX in CodeIgniter

I want my second selects options to vary depending on the choice in the first select.
If you pick "Skalman" you can't pick "Whole day with lunch" and if you choose "Lilleskutt" you can't choose "Half day".
I haven't worked with AJAX before but thinking that it might be the right way to go, if anyone could help me out I would be more than grateful!
I get the options from the database, using two functions in Booking.php:
private function get_room_options() {
$this->load->model('Booking_Model');
$rooms = $this->Booking_Model->get();
$rooms_form_options = array();
// get room title and store in array
foreach ($rooms as $id => $room) {
$rooms_form_options[$id] = $room->title;
}
return array(
'rooms_form_options' => $rooms_form_options,
);
}
public function get_package_options() {
$room = $this->input->post('searchData');
$this->load->model('Package_Model');
$packages = $this->Package_Model->get();
$packages_form_options = array();
foreach ($packages as $id => $package) {
$packages_form_options[$id] = $package->package_name;
}
return array(
'packages_form_options' => $packages_form_options,
);
}
And in my booking.php you find the form:
<?php
echo form_open('booking/preview') ?>
<div>
<?php echo form_label('Conference Room: ', 'id') ; ?>
<?php echo form_dropdown('id', $rooms_form_options, set_value('id')); ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id') ; ?>
<?php echo form_dropdown('package_id', $packages_form_options, set_value('package_id')); ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people') ; ?>
<?php echo form_input('number_people', set_value('number_people')) ; ?>
</div>
<div>
<?php echo form_submit('preview', 'Book'); ?>
</div>
<?php echo form_close(); ?>
And my script so far:
<script type="text/javascript">
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/booking/get_package_options'); ?>",
type: 'POST',
data: searchData,
success: function() {
// how should I get the options in here?
}
});
});
});
</script>
CodeIgniter doesn't support ajax.For more clarification http://phpframeworks.com/
So lets start from view
<?php echo form_open('booking/preview') ?>
<div>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<?php echo form_label('Conference Room: ', 'id'), form_dropdown('id', $rooms_form_options, set_value('id')) ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id'), form_dropdown('package_id', $packages_form_options, set_value('package_id')) ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people'), form_input('number_people', set_value('number_people')) ?>
</div>
<div>
<?php echo form_submit('preview', 'Book') ?>
</div>
<?php echo form_close() ?>
Here optimize your code by removing trailing semicolon & multiple echo
into single statement.
Now in your js part
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.post('YOUR_SEARCH_URL', { data : searchData }).done(function(data, textStatus, jqXHR) {
var h = '';
$(data.YOUR_SERVER_RESPONSE_KEY).each(function(i, v){
h += '<option value="' + i + '">' + v + '</option>'
});
$('[name=package_id]' ).html(h);
}).error(function(jqXHR, textStatus, errorThrown) {
//Handle your ajax error
});
});
});
Now at your controller
public function YOUR_CONTROLLER_ACTION() {
$data = $this->input->post('data');
//Do your work & get data from model for the id
//now send json response
return $this->output
->set_content_type('application/json')
->set_output(json_encode(YOUR_JSON_RESPONSE_ARRAY));
}
Check this two links http://code.runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php & http://code.tutsplus.com/tutorials/codeigniter-from-scratch-day-8-ajax--net-9243 for more details

Reload Specific <div> of page during ajax call

I got stuck on the following issue. the issue is, I want to reload particular div of my page that also contain PHP script. My javaScript function is
function select_dayoff() {
jQuery('#loader').css('display','block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"+"fschedules/dayoff";
jQuery.ajax({
type: "POST",
url: site,
data: "&fulldate="+MyDayoff.dayof,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
and DIV is:
<span id="fill_available_time">
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile">
<?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?>
</div>
<?php $form->end(null); ?>
</span>
I want to refresh this DIV during above Ajax call.
Thanks in advance for any help.
create a html file xyz.html and add the html code
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile"><?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?></div>
<?php $form->end(null); ?>
function select_dayoff() {
jQuery('#loader').css('display', 'block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"
+ "fschedules/dayoff";
jQuery.ajax( {
type :"POST",
url :site,
data :"&fulldate=" + MyDayoff.dayof,
success : function(msg) {
jQuery('#loader').css('display', 'none');
$('#fill_available_time').load('xyz.html')
}
});
}

Jquery, ajax and problem with load

This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.
When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.

Categories