Refreshing div with ajax causes checkbox to loose value - javascript

I have a small box that is part of a PHP-site that lists all members who attended a certain event. In the box there is also a checkbox that communicates with a database to store values of who attended. I want the box to update dynamically when someone checks the checkbox. The code I have is working good, and whenever the DIV is refreshed I get an updated list of members and correct count, but loose both the checkbox value and the label!
I am sure there is a simple solution I've missed, but after trying for hours I need someone to point me in the right direction. Whenever I press F5 to refresh, the label and correct checkbox value reappears.
Javascript:
function check_my_attendance() {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if (user_attending > 0) { $("label[for='attending_checkbox']").text("You attended!"); }
else { $("label[for='attending_checkbox']").text("You did not attend."); }
$('#attending_checkbox').prop('checked',user_attending);
}
function set_attendance(cb) {
if($(cb).is(":checked")) {
$("label[for='attending_checkbox']").html('Setting..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
else {
$("label[for='attending_checkbox']").html('Removing..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=0",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
}
$(document).ready(function(){
check_my_attendance();
});
</script>
PHP/Html:
<div id="containerAttend">
<?php $query_attendance="SELECT link_attending.attended_memberid,link_attending.attended_gigid,members.username FROM link_attending
LEFT JOIN members ON (members.id = link_attending.attended_memberid) WHERE attended_gigid=".$ut;
$result_attendance = mysqli_query($mysqli,$query_attendance);
$attending_users = array();
for( $i = 0; $i < mysqli_num_rows ($result_attendance); $i++)
{mysqli_data_seek($result_attendance,$i); $usr=mysqli_fetch_array($result_attendance); $attending_users[] = $usr["username"];}
$chkattendance = array_filter($attending_users);
if (empty($chkattendance)) {$attendance_int = 0;} else {$attendance_int = count($attending_users);}
?>
<div id="list_attended">
<div class="col-md-3 col-md-offset-5">
<div class="panel panel-default">
<div class="panel-heading">
<b><?php echo $attendance_int; ?> users attended:</b>
</div>
<div class="panel-body">
<?php
if ($attendance_int > 0) {foreach($attending_users as $usr_att) {echo "<a href='profile.php?user=$usr_att'>$usr_att</a>"." - ";} echo "<br>";}
if (login_check($mysqli) == true)
{echo "<form><input id='attending_checkbox' type='checkbox' onclick='set_attendance(this)' />
<label for='attending_checkbox'></label></form>";}
else
{echo "<br>Log in to set attendance!";}
?>
</div></div></div></div>
Thanks for any help!

Based on the comments, this is where I believe you can make changes and everything might just work fine for you
function check_my_attendance(result) {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if(typeof result != 'undefined') {
user_attending = result;
}
if (user_attending > 0) {
$("body label[for='attending_checkbox']").text("You attended!");
} else {
$("body label[for='attending_checkbox']").text("You did not attend.");
}
$('body #attending_checkbox').prop('checked',true);
}
In function set_attendance(), you can pass the result value to your check_my_attendance() function like this:
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance(result);
}
});
You can do console.log(result) and check what you are getting as result in in the after the AJAX Callback. If it is an empty string, you can add this line at the end of setattendance.php - echo 1; or echo 0;
I also created this fiddle as a small example for setting this checked property and label text. Even though I am not using any AJAX in it, I just wanted to let you know why we are using the body tag before #attending_checkbox in $('#attending_checkbox'). The basic reason behind showing it to you is that whenever a new DOM element is loaded or an old DOM element is replaced the old javascript doesn't work. So, you need to set the parent name and then the DOM id first, so that the JavaScript is able to locate the new element. - https://jsfiddle.net/prateekkathal/3kbtp2am/
Thanks,

Related

How refresh particular div without reload whole page?

<div id="success_hold">
<?php
if($row['mandate_end']!=date('Y-m-d') && $row['job_position']=='unhold')
{
echo '<span class="badge badge-success">Open</span>';
}
else
{
echo '<span class="badge badge-warning">Hold</span>';
}
?>
</div>
<script>
$(document).ready(function(){
var flag = 1;
$(".hold").click(function(){
job_id = this.id;
if(flag == 1)
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>pausehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 0;
}
else
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>resumehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 1;
}
});
});
</script>
I have div where id="success_hold". Now, what happens when I click on class="hold" I am updating my data. Now, I want to refresh my <div id="success_hold"> without reload whole page where I am using .load() function But the problem is that when I use .load() the function shows the whole page in success_hold. So, How can I fix this issue? I want to refresh only success_hold.
Thank You
The problem is because load() is used to make another AJAX request and place the a portion of the HTML retrieved from that request in the target element.
As you're already making an AJAX request to get the data, which is presumably HTML, you simply need to append() data to the container.
Also note that the only difference between the two sides of your condition is the URL the request is sent to, so you can easily DRY this code up:
$(document).ready(function() {
var flag = true;
$(".hold").click(function() {
var url = '<?php echo base_url(); ?>' + (flag ? 'pausehold' : 'resumehold');
flag = !flag;
$.ajax({
type: "POST",
data: { job_id: this.id },
url: url,
success: function(data) {
$("#success_hold").append(data);
}
});
});
});
If data contains the entire page, then you should change that PHP file to return only the relevant HTML as it will help to speed up the request. If, for whatever reason, you can't do that then you can extract the required element from the response like this:
$("#success_hold").append($(data).find('#success_hold'));
success:function(data){
$("#success_hold").load("#success_hold");
}
This is your success method in ajax. You want to pur the content of data into your div #success_hold ?
If you want that, just do this :
success:function(data){
$("#success_hold").html(data);
}

Reset the data after unchecking the checkbox

I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO

jQuery updates DOM, browser does not

I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.

mysql query executed even though fields are empty

I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>

Show/Hide doesn't work unless page is refreshed

EDIT: for clarity purposes, I've edited this question.
EDIT 2: I was able to solve half of my issue.
Below is a simple script for users to delete the pictures they uploaded.
Depending on whether or not there is an image saved in the database. A toggle OR an upload icon should show.
The issue is that when the delete button is clicked, the picture and the toggle buttons get removed BUT the upload icon won't show (unless page is refreshed).
if (image exists in database) {
<div class="toggle" id="toggle<?php echo $image_id ?>"></div>
}
else {
<div class="upload_icon" id="upload<?php echo $image_id ?>"></div>
}
`SQL query to select image in database`
//this DIV expands when the toggle button is clicked
<div class="content" id="image<?php echo $image_id ?>"><img src="<?php echo
$path ?>" />
<div class="remove content"><a href="#" id="<?php echo $image_id ?>"
class="delete_icon">Remove!</a></div>
</div>
Javascript part:
$(function(){
$('.delete_icon').on("click",function()
{
var ID = $(this).attr("id");
var dataString = 'image_id='+ ID;
$this = $(this);
if(confirm("Are you sure you want to delete this image ?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html){
$('#image'+ID).remove()
$('#toggle'+ID).remove()
$('#upload'+ID).show();
});
}
return false;
});
});
What am I missing here ?
this is no longer the link once you're inside the context of the success function. I saved off this and used it inside, that should do the trick.
Also I'm not sure that the find is actually going to work. Based on your example I'm not sure that #toggle elements are actualy nested within .delete_icon.
If they aren't you might want to do $('#toggle'+ID) rather than using find. It's an ID selector anyway so it wouldn't be affecting performance.
$(function(){
$('.delete_icon').on("click",function() {
var ID = $(this).attr("id"),
dataString = 'image_id='+ ID,
$this = $(this);
if( confirm("Are you sure you want to remove this image ?") ) {
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html) {
$this.closest(".content").hide();
$('#toggle'+ID).hide()
$('#upload'+ID).show();
}
});
}
return false;
});
});

Categories