I have been trying to create a chatting system using php+ ajax + mysql.
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name'];
?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function() {
var id = $(this).data("id1");
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: id
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
}
});
}
function myTimeoutFunction() {
fetch_chat();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
fetch_chat();
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: id,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
});
});
</script>
but the problem with this code is that it worked only for the first user I chat with but the screen starting blinking frequently when I click on other users' name. for example: user 'a' is logged in and click on user 'b' and starts the chat. everything works fine till now, but when user 'a' thinks to chat with a another user 'c' the whole chat part start blinking with all chats stored in database. plz tell me where I m goin wrong.
This needs a complete rethink really, to be rid of all the potential bugs.
The problem you describe above is because you're creating a new timed interval every time someone clicks on a name, so gradually this builds up and you are requesting every few milliseconds instead of every second. This is unsustainable. There's no need really to be declaring intervals, functions etc etc within the "click" handler of the name. I think you're doing this because of the dependency on the user ID which results from selecting a name. However you can overcome that by assigning the value to a global variable.
Doing this means you can move all the functions outside the click handler, removing any danger of re-creating the same intervals / events multiple times. I've also changed it so it doesn't use an interval. Instead, fetch_chat calls itself again 2 seconds after the previous response is received. That way, if a fetch takes longer than normal, you don't have multiple competing fetch operations running in parallel and causing potential confusion. I also increased the time interval to something which is still reasonable, but won't overload the server.
Here's a complete rework of your code:
<script>
var currentID = null;
var chatTimer = null;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
chatTimer = setTimeout(fetch_chat, 2000); //request the chat again in 2 seconds time
}
});
}
$(document).ready(function() {
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
clearTimeout(chatTimer);
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
fetch_data(); //this will also trigger the first fetch_chat once it completes
});
</script>
P.S. If you want anything faster than 2 seconds refresh, then really you probably need to consider re-architecting the solution using websockets to get full 2-way communication, so the server can "push" chat items to the client instead of the client having to poll the server.
You are using setInterval, this is wrong, this will start a loop every time you click on a chat, you should have a single loop running over all your chats. Also consider using setTimeout instead of setInterval to ensure you get the response first.
Related
How to show "Live Feedback" on a script using jQuery?
I have a button that I use to submit a form for processing. Processing takes a long time. I want to have a <div id="progress"></div> where I show live progress report of what order processing script is doing. If all goes well I want to redirect to the View Order script, and if not, just show the progress report (not redirect to view order)
How? Currently I have this:
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
});
and even though I have print statements in my process_order file, they are not being displayed anywhere on the screen. Well, of course not ... I don't know how to build my jQuery/AJAX to make them show.
I am not sure how to proceed.
You would need to start the long process and then start a timer to poll the status. Keep in mind it doesn't take much for this to become more expensive than it's worth.
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
setTimer($.ajax({
type: 'post',
url: 'view_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").append(data);
}
}), 30000); //check every 30 Seconds
});
I have a news feed on my site, onto which users can post posts. These posts can then be liked by other users (just like facebook for example).
The Problem
I would like to display the users, who liked a post using ajax. Whenever a certain element is hovered.
At the moment the users are correctly displayed but below every post, not just the one which contains the hovered element.
My attempt to solve the problem
<!-- HOVER THIS -->
<span class="likers small link"></span>
<!-- DISPLAY LIKERS HERE -->
<small class="displayLikers"></small>
<!-- AJAX -->
<script>
$(function() {
$(".likers").hover(function(){
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
$(this).closest('.displayLikers').html(response);
}
});
});
});
</script>
I would be very thankful for any kind of help!
Inside the $.ajax, $(this) does not refer to $(".likers") just add $(this) to a variable and use it in the ajax response function;
$(function() {
$(".likers").hover(function(){
var likes = $(this);
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
likes.closest('.displayLikers').html(response);
}
});
});
});
In your example the .displayLikers is a sibling so you should probably use next(). Moreover this will refer to the actual context of the success function, so you have to create a reference before.
$(function() {
$(".likers").hover(function(){
var self = $(this);
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
self.next('.displayLikers').html(response);
}
});
});
});
I'm trying to use setInterval to execute the php script update.php every 10 seconds and refresh div id = verification. For some reason setInterval is preventing the script from functioning. Any suggestions on where to place\change setInterval would be appreciate as I'm stumped (sorry entry level javascript user here). For clarity I omitted all the non-relevant details, such as vars.
<div id="verification"></div>
<script id="verification" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
});
setInterval(10000); //every 5 secs
</script>
Suggestions/Steps/Bugs:
Create a separate function to perform ajax request
Call this function on page load to run it when page is loaded
Use setInterval() to call the function every n seconds
id should always be unique. You're now using verification as if for <div> and <script>
You can remove id and language attributes of <script>. Those are not required.
Code:
function update() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function (data) {
//on receive of reply
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
}
$(document).ready(update); // Call on page load
// ^^^^^^
setInterval(update, 10000); //every 10 secs
// ^^^^^^
setInterval() takes a function (that it should execute) as it's first argument.
Try this:
setInterval(function(){
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>"+foobar+"</b>)"); //output to html
}
});
}, 10000);
you are using setInterval in a wrong way - you can read about it here:
http://www.w3schools.com/js/js_timing.asp
Also please notice that AJAX calls are asynchronous - when program is going forward it doesn't mean that previous AJAX call has ended. You can "wait" for AJAX completition using some jQuery mechanisms like binding ajaxComplete or using when
You are missing the function block:
setInterval(function() {
// to do
}, 5000);
My suggestion is to go for setTimeout as you are running ajax it is not certain that it would complete within 5 seconds. In case if you wana go for it:
var dispatchUpdates = function() {
setTimeout(pullUpdates, 5000);
};
var pullUpdates = function() {
$.ajax({
url: 'update.php',
data: "",
dataType: 'json',
success: function(data) {
var foobar = data[2];
$('#verification').html("(<b>" + foobar + "</b>)");
dispatchUpdates(); // next updates
},
error: function() {
dispatchUpdates(); // retry
}
});
};
$(dispatchUpdates); //page load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I have a list of results that are shown on a particular page and these are updated at regular intervals using a simple AJAX request. An input form allows me to filter these results, but as the data is updated every few seconds, the input form doesn't work properly as it refreshes all the data. Is there any way for the AJAX to not update when there is a value in the form input field?
Below is the HTML code:
<div id="my-query-results" class="visible">
<div>
<form class="searchboxInput" action="#">
<input id="kwd-my-query-results" type="text" value="">
</form>
</div>
<div id="my_recent_queries">
<span class="loading_placeholder">Loading ...</span><br />
<img src="../img/ajax-loader.gif" />
</div>
</div> <!-- my query results -->
Below is the AJAX request that I was using:
if( $("#kwd-my-query-results").val() != "") {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 600000);
}
updateMyQueries();
} else {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 4000);
}
updateMyQueries();
}
The above if else statement just didn't seem to work. It would evaluate to the else statement once a value was present in the input box. I think I also tried length(), but that didn't seem to work either. Any other way of approaching this?
Update
I tried the following given the suggestion below, and it works to some degree. It loads the results initially, allows me to search them without reloading the data, but then it doesn't reload the results at regular intervals, even when there is no text in the input field...
$(function(){
setTimeout(updateMyQueries(), 4000);
});
function updateMyQueries(){
if ($("#kwd-my-query-results").val() == "") {
// do ajax call
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
}
}
I would start by moving the updateMyQueries function out of the if statement then maybe something like this.
$(function(){
SetInterval(updateMyQueries(), 4000):
})
function updateMyQueries(){
if($("#kwd-my-query-results").Val() == ""){
// do ajax call
}
}
EDIT - this will work
setInterval(function (){
if($("#search").val() == ""){
// Ajax call here
}
}, 4000);
I'm trying to implement simple Comet chat example and for this I implemented Long polling which calls itself recursively every 30 seconds.
When pressing on button I want another ajax request to send new data on Server using POST.
For now I just put alert to this function to trigger click event
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$("#postMessage").click(function () {
alert("request");
});
$.ajax({ dataType: 'json',url: "CometServlet", success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
}, complete: poll, timeout: 30000 });
}
$(document).ready(polling)
</script>
And my HTML is like this:
<div>
<input type="button" id="postMessage" value="post Message">
</div>
<div id ="message" name="message"></div>
When I click on button my alert is shown several times. Why? How can I solve it?
As Dave mentions, that's not what the timeout option is for. Try something using setTimeout instead. Also, you're mixing your polling logic and your click handler (I think). Here's how you would separate them:
function poll() {
$.ajax({
dataType: 'json',
url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: function () {
setTimeout(poll, 30000);
}
});
}
$(document).ready(function () {
$("#postMessage").click(function () {
alert("request");
});
poll();
});
Example: http://jsfiddle.net/VyGTh/
In your code after every Ajax call you re-bind click event to #postMessage and that's why you had couple of alert messages. You need to bind click only once in page load. You can fix it by doing something like:
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$.ajax({ dataType: 'json',url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: poll,
timeout: 30000
});
}
$(document).ready(function(){
// Now Click only binds one time
$("#postMessage").click(function () {
alert("request");
});
polling();
});
</script>