How i could make this page auto refresh/update every 10 second when there is/isnt data update. Like Twitter when there is a new tweet.
Example : This is in first second.
You have 1 name with no status
Then after 10 second, there is an event that "name" data have been added.
You have 2 names with no status
what should i do? I've tried with javascript, but it wont refresh the data from controller.
this is my actioncheckNames Controller
public function actioncheckNames() {
//Check Name with No Status
$noStat = new CDbCriteria();
$noStat->condition = "status IS NULL";
$noStat->order = "name ASC";
$sums = Name::model()->count($noStat);
//End of Check Function
return array('sum'=>$sums);
}
And this is sort of my index on view.
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: '<?php echo $this->createUrl('name/checkNames'); ?>'
, type: 'post'
, success: function(data) {
if (data) {
$("#checkname");
}
}
});
}, 5000 //5 seconds
);
});
</script>
<div id="checkname">
<?php
if ($sum != 0) {
?>
<div class="alert alert-block alert-primary fade in">
<button data-dismiss="alert" class="close" type="button">X</button>
<h4 class="alert-titleing">You Have <?php echo $sum ?> Names With No Status. <font color="White"><u>Check</u></font> </h4>
</div>
<?php }
?>
</div>
*Update : create actionCheckNames Controller and add ajax script. but my web wont refresh the data.
You can refresh your page by JS set interval + AJAX request & can try something like below
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: '<?php echo $this->createUrl('controller/action');?>'
,type: 'post'
//,data: {var1: val1, var2: val2,....}
,success: function(data){
if(data){
//Refresh your div/html element by appending here...
}
}
});
},10000 //10 seconds
);
});
Related
Having problem to change the state if its active or inactive everytime I clicked one of them nothings happened.
This is my code on ajax.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? '0' : '1';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
my php code ajax.php
<?php $db= new mysqli('localhost','root','password','dbname');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>
this is my code for displaying it, on this part everything works fine, when the value are 0 it will display inactive and 1 for active, however when clicking the status theres nothing happen only the notification and reload the page.
<td><i data="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
</i></td>
Try to configure your code to:
$(document).on('click','.status_checks',function(){
var status = '1';
var msg = 'Activate';
if($(this).hasClass("btn-success")){
status = '0';
msg = 'Deactivate';
}
if(confirm("Are you sure to "+ msg)){
var id= $(this).data('id');
url = "/ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:id,status:status},
dataType: "json",
success: function(data)
{
console.log(data);
location.reload();
}
});
}
});
<?php $db= new mysqli('localhost','root','password','dbname');
$user_id=$_POST['id'];
$newStatus=$_POST['$status'];
$sql = "UPDATE user SET status=".$newStatus." WHERE id=".$user_id."
";
if($db->query($sql) === TRUE){
echo json_encode(1);
}else{
echo json_encode(0);
}
?>
<td><i data-id="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' :
'Inactive'?>
</i></td>
I have buttons that add and remove products from the Magento cart, but that's not so relevant in that issue. What I want to do is change the logic of what they are doing. Currently, when the buy button is clicked, the product is added to the cart, the button is "changed" to remove it and all other buttons are disabled for the click. When the remove button is clicked, the product that was added is removed and all other buttons can be clicked again.
I want to change the logic to the following: when the buy button is clicked, the product is added to the cart and the buy button is "changed" to remove (so far everything is the same as it was). But, all buttons remain click-enabled and if any other buy button is clicked, the product that was added is removed and the new product is added.
I've researched and thought in many ways, but I can not find a way to do that.
Button code:
<button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remover</span></span></button>
Ajax requisition code:
function addCartao(product_id){
$j('#cartaoMensagem'+product_id).hide();
$j('#cartaoMensagemRemover'+product_id).show();
$j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product_id: product_id
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product_id);
$j('#cartao').find(':button').not(button).attr('disabled',true);
$j('.item-custom').append('<tr id="trAppend"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
function removeCartaotoCart(itemId){
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartao').find(':button').attr('disabled',false);
$j('.item-custom #trAppend').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
I "simplified" your code a lot... Since I can't make an example with your PHP.
So the "reproduced" behavior is in this CodePen.
Now what you need to do, is to keep the added product ID in "memory" in a variable.
On add... If there already is a product ID, call the remove function, then add the other product.
It should be as simple as this.
So here is another CodePen with th modifications to make.
var productSelected = ""; // The variable used as a "memory".
function addCartao(product_id){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
console.log("Add "+product_id);
productSelected = product_id; // Keep the product id in "memory".
$('#cartaoMensagem'+product_id).hide();
$('#cartaoMensagemRemover'+product_id).show();
$('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000','color':'white'});
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+product_id);
//$('#cartao').find(':button').not(button).attr('disabled',true); // Do not disable the other buttons.
}
function removeCartaotoCart(itemId){
console.log("Remove "+itemId);
productSelected = ""; // Remove the product id from "memory"
$('#cartaoMensagemRemover'+itemId).hide();
$('#cartaoMensagem'+itemId).show();
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+itemId);
//$('#cartao').find(':button').attr('disabled',false); // The other buttons aren't disabled... This line is useless.
}
I am working on a small social network project where I am using post comment functionality. What I am stuck with is as soon as the use deletes a comment, the comment count should decrease automatically. This can onyl be done using refresh functionality, but the current code does not seem to be working. It deletes the comment but does not display the decreased count. So whenever a comment is deleted, it should show up the decreased count. Here is my code so far.
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
View all <?php echo $comment_count; ?> comments
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
JQuery
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$('.comment_ui').load(url + ' .comment_ui');
}
});
return false;
});
});
</script>
Try Below code
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$.post( url + ' .comment_ui', function( data ) {
$( ".comment_ui" ).html( data );
})
},
error: function(){
alert("somthing is wrong")
},
});
});
});
</script>
You cant use .load() like that. The variable url isn't defined and you can't add a jquery selector to the url.
If you cant .load() the exact html you need you must .get() it instead, .find() the part you need in the response and insert it with .html()
EDIT: Added code suggestion
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all
<span id="totalCommentsCount"><?php echo $comment_count; ?></span> comments</a>
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".delete_comment").click(onDeleteComment);
});
function onDeleteComment() {
var commentElement = this;
var commentId = commentElement.id;
//Start the fade-out even before the delete is committed to create a fast user experience
var commentRow = $(commentElement).closest('.comment_text');
commentRow.fadeOut('slow', function() { commentRow.remove(); });
//Post the delete to the server
$.ajax({
type: "POST",
url: "delete_comment.php",
data: { comment: commentId },
success: function (deleteResponse) {
//USE ONE OF THE ALT. BELOW:
//Alt.1: delete_comment.php returns a json like { count: 12 } which describes number of comments left
$('#totalCount').text(deleteResponse.count);
//Alt.2: you don't care to reload number of comments from server and just decrease by one.
var totalCountSpan = $('#totalCount');
totalCountSpan.text(parseInt(totalCountSpan.text()) - 1);
//Alt.3: get number of comments left on server by reloading the "view" an extra time. Really not optimal!
var viewId = $('.comment_ui').attr('id');
$.get( "get_view.php?id=" + viewId, function( data ) {
var newCount = $(data).find('#totalCount').text();
$( "#totalCount" ).text( newCount );
});
},
error: function(){
//Possibly restore the comment here if this happens often?
alert("somthing is wrong")
},
});
}
</script>
I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});
I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>  <input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span>   <input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}