Append old chats before new chats to the div using jQuery - php

In my online-chat project using Codeigniter, jQuery, AJAX I have a function that runs every 1 second which retrieves chat with delivered status = 0
$.post("<?php echo base_url(); ?>chat/admin_chat/get_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
if (data != "") {
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
}
);
and there is another function which is used to get the chats with delivered status = 1 (or old chats),
$(document).on('click','.user',function (e) {
e.preventDefault();
$('.username').html($(this).text());
$('.hide_me').html($(this).attr('id'));
$('.username').show();
$('.log_username').hide();
$("#input").removeAttr("readonly");
var user = $(this).attr('id');
$("#chat_window").html('');
$.post("<?php echo base_url(); ?>chat/admin_chat/get_old_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
);
});
which is called when clicked on the username. The result of both AJAX calls are appended to a div. The problem I face now is sometimes when I click on the username, the chats that are not delivered is getting appended to the div before the old chats which is not what I want. I need the old chats to be appended to the div before the new chats, when clicked on the username. Could someone please suggest a way to fix the issue?

At last I found a way to fix the issue.
I added a span <span id='old_chat_appended' hidden=""></span>.
Modified the get_old_chat function a little bit by changing the value of span to 0 and 1.
After e.preventDefault(), added
$('#old_chat_appended').text('0')
and after appending data to div using $('#chat_window').append(data), added
$('#old_chat_appended').text('1').
At last in the get_chat function, which runs every 1 second, added
if($('#old_chat_appended').text() == 1)
{
$('#chat_window').append(data);
}
The application is working as expected. The old chats are getting appended to the div before the new chats.

Related

How to use onclick on a button with an insert function for multiple buttons php

I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.

Unable to delete more than one cart items

I have developed a shopping website where i am using ajax to process add to cart and remove from cart. Add to cart is working fine but remove from cart is creating an strange issue. I am able to delete only one record from it and if i want to delete more i need to manually refresh the page and then i would be able to delete only one more. This is so strange and i am unable to find where the bug is.
here is the code :
jQuery('.remove').click(function(data) {
var pi = jQuery(this).attr('name');
var y = jQuery(this).attr('name');
$.ajax({
url: "delcart.php?pid="+pi+"&data="+y,
type: 'GET',
success: function(s){
var $container = $("#content");
// $container.refresh("index.php");
$("#content").load(location.href + " #content");
$("#success2").show().fadeOut(6000);
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
HTML Button.
<button name="<?php echo $ca['ID'];?>" class="remove close_product color_dark tr_hover">x</button>
this button is into the while loop and each time name property consisting the unique ID of database cart table.
here is the delcart.php :
<?php
include_once "config.php";
$id = $_GET['pid'];
$ip = $_SERVER['REMOTE_ADDR'];
$de = mysqli_query($con,"DELETE from cart where ID='{$id}' and ip='{$ip}'");
?>
can anyone please figure what have i missed or where the bug is. This would be a huge help. Thanks in advance.
Not sure if I have the solution for you but I guess it's worth a shot.
My guess is that your buttons with class remove are located somewhere in div with id of container, correct?
if so, then you "lose" the .click handler when you call the .load function that replaces the content of #container div.
the solution would (could) be to change the .click listener to sth like
$('#some-div-container-that-stays').on("click", ".remove", function(data) {
Or at least try to put an console.log() into the .click action to see if it triggers or not

select2 to add new tags with confirmation box

In Select2 I have basic tagging functionality working. The tagging system is works in an insert project page, where I can tag projects with certain predefined tags that are stored in a database and called by AJAX, and also in an update project page where the same mechanism is at play with the addition of bringing up currently stored tags in the tag field.
I want it so that if no tag currently exists, the user will receive a confirmation box that asks whether or not they want to add a new tag, and by hitting ok that tag will then be stored in the database. There should also be a sort of buffer time of a few seconds for Select2 to catch up with looking up the tags otherwise it might create duplicates?
I have read something here that shows how to do the jquery part, albeit its incomplete for my purposes. Can anyone shed light into how I might do this? I am not looking for complete answers, but merely guidance.
Have a look at this question: How do I fire a new ajax on select2 new /remove tag event?
In your case, using your fiddle, you can use something like:
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
// A new tag was added
// Prompt the user
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
// User clicked OK
console.log("Sending the tag to the server");
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
} else {
// User clicked Cancel
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
Draft fiddle here.

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

How to show users that a new comment has been entered

I have a small blog that I am creating. It gets its information from a database. I would like to show the users that are logged in that someone else has just entered a new comment. I have created 3 pages: old_count, new_count, posts. I was going to create a session for both new_count and old_count and subtract them in posts. The result would have been displayed in a div to the user. This idea I have scrapped because both old_count and new_count would have the same information, so the result in posts would have always been 0. What I am looking for is something like Twitter where if there is a new entry, a div appears displaying --1 New post--. I have being looking for a way to do this. Can someone please help me. (Note - please explain script given in full....Thanks In Advance!!!!)
Set a timestamp of the last time they checked for content.
then, using javascript, poll the server (SELECT * FROM posts WHERE created_timestamp > {$last_checked_timestamp}
If result > 0 then display count.
Update timestamp.
The question is: When is a comment a new comment? If it has been created between the most recent click and the current click? Or if the user has not yet seen it?
The easiest way will be to store the "known" comments (e.g. IDs) in the session and check against the currently available comments.
You would have to store the login timestamp user. Maybe in DB or in session. Check it against the comment timestamp.
You have to display notifications for all the comments that have been inserted in the database and stick to following conditions
Comment_Timestamp < User_Login_Timestamp.
(Current_Timestamp - Comment_Timestamp) <= Refresh_interval
PHP:
<?php
/*
DB CONNECT AND SQL TO SELECT COMMENTS FROM THE TABLE. YOU CAN OPTIMIZE QUERY TO REDUCE THE NUMBER OF
TUPLES
*/
$current_ts = strtotime(date('m/d/Y h:i:s a');
$notified = array();
foreach($all_comments as $comment) {
if(strtotime($comment['ts']) < strtotime($_SESSION['user_login_ts'])) {
if(($current_ts - strtotime($comment['ts']) <= REFRESH_INTERVAL) {
$notified[] = $comment;
}
}
}
echo json_encode($notified);
?>
JS AJAX
setInterval(function(){
$.ajax({
url: "server",
success: function(data) {
/* Data is the JSON Object for new comments for that user */
},
dataType: "json"
});
}, <?=REFRESH_INTERVAL?>);
With the suggestion that was posted by David, I came up with the following solution to the questions that I had asked earlier.
I created a timestamp upon login.
I then use this to run the search on the database.
The DIV containing this information is being refresh every 10 secs and is a clickable link to a timestamp reset page. The code for this page is as follows:
<?php
session_start();
$reset = $_POST['reset'];
if($reset == 'reset')
{
$_SESSION['time_stamp'] = time();
echo "done";//confirmation purpose
}
?>
and my javascript that controls the whole show:
<script type="text/javascript">
<!--
$(document).ready(function(){
$('#divname').click(function(){
var r="reset";
$.ajax({
type: "POST",
url: "reset_time.php",
data: r,
success: function(html){
if(html == 'done')
{
$('#divwithinfo').reload(/*my blog page url*/);
}
});
});
});
-->
</script>

Categories