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);
}
})
});
Related
I want to change the status (Active/Deactive) of records in database without actually submitting(refreshing page) data, using jquery.
In my script Status is getting changed in database but as it is not refreshing, display status is not updating. is there a way to display the changed status without refreshing? i mean as soon as it updates in database, it should reflect in the status.
Here is my script
<table class="table table-bordered table-condensed table-striped mb-6">
<thead>
<tr>
<th>Firstname</th>
<th>Mobile</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
//$CQuery = ""; my query
while($ConRow = DB_fetch_array($CQuery ))
{
?>
<tr>
<td><?php echo $ConRow['fname']; ?></td>
<td><?php echo $ConRow['mobile']; ?></td>
<?php if($ConRow['status']=='A') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button> </td>
<?php } else if($ConRow['status']=='D') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button> </td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
Script
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var data1 = 'id=' + del_id;
if (confirm("Sure you want to De-Activate this?.")) {
$.ajax({
type : "POST",
url : "DisableContact.php",
data : data1,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
PHP
$id = $_POST['id'];
$sel1 = "SELECT status FROM contacts WHERE con_id=".$id."";
$Sel = DB_query($sel1);
$srow = DB_fetch_array($Sel);
if($srow['status']=='A')
{
$sql = "UPDATE contacts SET status='D' WHERE con_id=".$id;
}
else
if($srow['status']=='D')
{
$sql = "UPDATE contacts SET status='A' WHERE con_id=".$id;
}
$result = DB_query($sql);
In database , Status is getting changed, but in table it is not showing up.
//Updated
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to De-Activate this?.")) {
$.ajax({
type : "POST",
url : "DisableContact.php", //URL to the delete php script
data : info,
success: function(data) {
var d = $.trim(data); //triming value if there is any whitespaces
if (d == "A") {
//means data is activate so show that button
$("#"+del_id+ ".btn-success").show();
//hiding other
$("#"+del_id +".btn-danger").hide();
} else {
//show deactivate buttton
$("#"+del_id +".btn-danger").show();
//hide other button
$("#"+del_id +".btn-success").hide();
}
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
PHP
if($srow['status']=='A')
{
$sql = "UPDATE cust_contacts SET status='D' WHERE con_id=".$id;
echo 'A';
}
else
if($srow['status']=='D')
{
$sql = "UPDATE cust_contacts SET status='A' WHERE con_id=".$id;
echo 'D';
}
$result = DB_query($sql);
You can pass some value from php to ajax call and depending on that the required button will get displayed .So your php code will look like below :
..
if($srow['status']=='A')
{
$sql = "UPDATE contacts SET status='D' WHERE con_id=".$id;
echo "D";//will get passed as response to ajax
}
else
if($srow['status']=='D')
{
$sql = "UPDATE contacts SET status='A' WHERE con_id=".$id;
echo "A";//will get passed to ajax as response
}
Your ajax success function will look like below :
..
success: function(data) {
var d = $.trim(data); //triming value if there is any whitespaces
if (d == "A") {
//means data is activate so show that button
$("#"+del_id+ ".btn-success").show();
//hiding other
$("#"+del_id +".btn-danger").hide();
} else {
//show deactivate buttton
$("#"+del_id +".btn-danger").show();
//hide other button
$("#"+del_id +".btn-success").hide();
}
}
Update 1:
As you have use if-else to show button so i forgot here that other button will not exist in this case thats the reason jquery is not able to find other button and display blank.Now, to solve this you need to make some changes in your php code where you are displaying your table.Changes you need to make are as follows :
Change this :
<?php if($ConRow['status']=='A') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button> </td>
<?php } else if($ConRow['status']=='D') { ?>
<td><button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button> </td>
<?php } ?>
to below :
<td> <div class="<?php echo $ConRow['con_id']; ?>"> <?php if($ConRow['status']=='A') { ?>
<button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-danger btn-sm">De-Activate</button>
<?php } else if($ConRow['status']=='D') { ?>
<button id="<?php echo $ConRow['con_id']; ?>" class="delbutton btn btn-success btn-sm">Activate</button>
<?php } ?> </div> </td>
Now ,in ajax success function we will use .html to add button inside <div></div> .So ajax will look like below :
if (d == "A") {
$("." + del_id).html('<button id="' + del_id + '" class="delbutton btn btn-danger btn-sm">De-Activate</button>');
} else {
$("." + del_id).html(' <button id="' + del_id + '" class="delbutton btn btn-success btn-sm">Activate</button> ');
}
How can i post data in Codeigniter using Ajax, am so confused this is the first time i do ajax and Codeigniter together
here is my ajax code
i tried to send the data to the controller method ;
This is my ajax
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url: baseURL+"admin/Products/add_product",
type:'post',
data:{productData:postData},
success:function(data){
}
});
});
});
this is my form
<?php $attribute = array( 'id'=>'register_form','form-horizontal'); ?>
<?php echo form_open('admin/products/add_product',$attribute); ?>
<?php echo form_label('product title'); ?>
<?php echo form_input($data_product_title); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product description'); ?>
<?php echo form_textarea($data_product_description); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product price'); ?>
<?php echo form_input($data_product_price); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product quantity'); ?>
<?php echo form_input($data_product_quantity); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_submit($data_3); ?>
<?php echo form_close(); ?>
Hope this will help you :
Your ajax script should be like this : , make sure your URL is correct
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url : baseURL+"admin/Products/add_product",
type:'post',
data: postData,
success:function(data)
{
console.log(data);
}
});
evt.preventDefault();
});
});
In your add_product method get post values like this :
public function add_product()
{
print_r($this->input->post()); // to print all post values
exit;
}
For more : https://www.codeigniter.com/user_guide/libraries/input.html
`$('#add').click(function() {
var form_data = {
subject_name: $('#subject_name').val(),
section: $('#section').val(),
grade: $('#grade').val()enter code here
};
$.ajax({
url:"<?php echo site_url('ViewCourses/SavingData');?>",
type:'POST',
data: form_data,
success: function(msg) {
if (msg == 'Yes')
document.location.reload(true);
else if (msg == 'No')
document.location.reload(true);
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg+'</div>');
}
});
return false;
});`
add Its Button Id Pe Use Of Onclick Function For Submit values With Ajax
form_data All Form Fields Of the Form
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>
I want to display a time in place of button when button clicked then
button fadein and time show in place of button but my script not
working button fadein only and time didn't show in place of button and
"Time shown when i refresh the whole page but not a particular part
refreshing."
foreach($leads as $val):?>
<tr><td class = 'account-name sort-value'>
<span style='float:left;width:47%;'>
<?php echo $val->first_name .' '. $val->last_name;?></span>
<?php
if($val->checkin_time != '') {?>
<span class = 'Dischktime' id = 'dischktime{<?php echo $val->lead_id;?>}' ><?php echo $val->checkin_time;?>
</span>
<?php
}
else {?>
<span style='float:left;width:26%;'>
<button id ='checkin{<?php echo $val->lead_id;?>}' class='btn btn-default' name='checkinbt' value='<?php echo$val->lead_id; type='button'>CheckIn
</button>
</span>
<?php }
?>
<span>
<?php echo $_SESSION['drivername'];?>
</span>
</td></tr>
<?php endforeach;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("[id=checkin]").on("click" , function() {
//$(this).fadeOut();
$(this).fadeOut('slow', function() {
//alert("it's working");
$("#dischktime").show();-------(Not working)
});
$('button').submit(function(e) {
e.preventDefault();
return false;
});
//alert($(this).attr('value'));
var lead_id = $(this).attr('value');
//alert(lead_id);
$.ajax({
method: "POST",
url: 'search_db_test.php',
data: 'checkinbt=' + lead_id,
success: function(data) {
$(this).html(data);
//$("#dischktime").show(data);-----(Not working)
}
});
});
});
</script>
You are creating element based on condition. When button is shown your Time span having id : dischktime is not created and thus its not available in DOM. Modify you foreach :
foreach($leads as $val):?>
<tr><td class = 'account-name sort-value'>
<span style='float:left;width:47%;'>
<?php echo $val->first_name .' '. $val->last_name;?></span>
<?php
if($val->checkin_time != '') {?>
<span class = 'Dischktime' id = 'dischktime{<?php echo $val->lead_id;?>}' ><?php echo $val->checkin_time;?>
</span>
<?php
}
else {?>
<span style='float:left;width:26%;'>
<button id ='checkin{<?php echo $val->lead_id;?>}' class='btn btn-default' name='checkinbt' value='<?php echo$val->lead_id; type='button'>CheckIn
</button>
</span>
**<span style="display:none;" class = 'Dischktime ' id = 'dischktime{<?php echo $val->lead_id;?>}' >**
</span>
<?php }
?>
<span>
<?php echo $_SESSION['drivername'];?>
</span>
</td></tr>
<?php endforeach;
}
Try Css Property
$("#dischktime").css('display', 'block') instead of $("#dischktime").show();
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>