develop Chat module in php, mysql and ajax jquery - php

I am trying to implement a small chat application where user can text chat with any one of the online users.
My logic behind this is some thing like the following:
Login first.
Fetch the users who are online from DB and show them as list of online users.
Click on the users, then another small window is opening for text chatting.
Create a form(two hidden fields- one is for sender id and another is for receiver id, one textarea and a button for submitting) for this chatting.
Through jQuery, fill the value of receiver id.
By session id, fill the value of sender id.
After submitting the button, I call a page through ajax jquery which is responsible to insert and show the current data from DB.
My code for the ajaxJquery is like :
$(document).ready(function(){
$('#send_btn').click(function(){
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
$.ajax({
type:"POST",
url:"chat_history.php?receiver_id="+receiver_id+"&sender_id="+sender_id+"&message="+messagebox,
success:function(result){
$('#history').html(result);
}
});
$('#messagebox').val('');
});
});
</script>
Up to this, its working fine. But I need to autoload the <div id="history"></div> portion. For that also I am thinking to do by using setInterval() in jQuery. My code is like :
<script type="text/javascript">
var auto_refresh = setInterval(
function (){
$('#history').load("chat_history.php?receiver_id=''&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
</script>
But in this scenario, how to pass the value of receiever_id in load() which is necessary to find out the respective data from DB?
Please let me know whether the requirement is cleared to you or not.
Thanks in advance.

<script>
$(function () {
// function wide variables
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
// button click
$('#send_btn').click(function () {
receiver_id = $('#hide_receiver_id').val();
sender_id = $('#hide_sender_id').val();
messagebox = $('#messagebox').val();
$.ajax({
type : "POST",
url : "chat_history.php?receiver_id=" + receiver_id + "&sender_id=" + sender_id + "&message=" + messagebox,
success : function (result) {
$('#history').html(result);
}
});
$('#messagebox').val('');
});
var auto_refresh = setInterval(function(){
$('#history').load("chat_history.php?receiver_id="+receiver_id+"&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
});
</script>

Related

Can I nest clicks for ajax calls within previously appended call results?

I'm making some early attempts at educating myself in AJAX and trying to speed pages rather than relying on PHP to show results. I have hit a hurdle.
I essentially have 3 tiers of data. With 3 database tables.
The first tier of data is pulled via a PHP loop and displayed upon page load.
The second tier of data is loaded via AJAX when A is clicked and then appended to the page via jQuery.
The third tier (where I'm having trouble) is loaded via AJAX when the second tier is clicked...and appended within the previously appended B data.
Like so....
<!-- language: lang-html -->
<!-- PHP loop to pull list if Item A data upon page load -->
<p>Item A</p>
<!-- click Item A -> AJAX pull B data and append results to .a-results -->
<div class="a-results">
<p>Item B</p>
<!-- click Item B -> AJAX and append results to .b-results -->
<div class="b-results">
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
</div>
</div>
Ajax examples:
<!-- language: lang-js -->
$('a.a-call').click( function (e) {
e.preventDefault();
var sid = $(this).attr('data');
$.ajax({
url: 'secondtier.php',
type: 'POST',
dataType: 'json',
data: ({sid: sid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var type = row[2];
$('.a-result').append("<p><a href='#' id='s"+id+"' data='"+id+"' class='b-call'>id: " + id + " name: " + name + " type: " + type + "</a></p><div class='b-data'></div>");
}
}
});
});
$('a.b-call').click( function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
My AJAX calls work in themselves, however I can't get the B call to append results within the A results. The Item B AJAX works just fine if it's hard coded into the HTML, it's only when it's appended that I can't get it work. No console errors anywhere. Just nothing happening on the page.
I'm not totally current on jQuery usage. I tried .live('click', function() for the Item B click, however the console is telling me it's not valid. I assumed jQuery dropped that at some point.
Using google to link to jquery 1.9.1
<!-- language: lang-html -->
<script language="Javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Am I going about this wrong? Can I get the appended anchor in B to call another ajax function and append more to the previously appended div?
I don't want to load all this data at once. This is my very reason for learning AJAX. The page currently loads everything via PHP and due to the amount of datasets within datasets it's a slow page load. I'm trying to get specific data to only load upon a click.
You need to use delegate() , because .b-call elements does not exist on page load, so jQuery doesnt know where those elements are. So you need to delegate an event to an element that will exist after page load.
$('.a-result').delegate('.b-call','click',function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
I think the problem is due to the fact that the link for fetching the B data is created when A is fetched.
The click event handler ($('a.b-call').click) is registered before the actual DOM element exists and therefore it does not get triggered.
To get this event handler working you need to change your code. The a-results div exists on page load, so you can attach the event handler to this element and simply specify the selector for a.b-call:
Example:
$('.a-results').on('click', 'a.b-call', function(e) {
// your B load code here
}

PHP/MySQL How to send result back to form?

So I got this form which lets the user enter up to 10 item IDs and then check for the status or apply changes right away. If the user clicks check status the item IDs will be sent to another PHP.
What is the easiest way to send the result back to the form and display it in the red area?
if ($_POST['action'] == 'Check Status/Shelf') {
$itemids = "$itemID1, $itemID2, $itemID3, $itemID4, $itemID5, $itemID6, $itemID7, $itemID8, $itemID9, $itemID10";
while ($row = mysql_fetch_array($all)) {
$hyllplacering = $row['Hyllplacering'] . "";
$all = mysql_query("SELECT Hyllplacering, itemID FROM booking WHERE itemID IN ('$itemids')");
}
}
If you don't want to use Ajax, then save the details into a $_SESSION[] and upon submission the form is posted and then the details can be populated into SESSION and displayed back out to the form upon reloading, but it's a bit of a fiddle for not much return.
And use MySqli or PDO.
For that you have to use ajax
Give id to Apply Changes & Check Status/Self button
<script type="text/javascript">
$(document).ready(function(){
$('#apply').click(function() {
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//same for all your 10 field
var cstring = "id1="+id1+"&id2="+id2 // etc;
$.ajax({
type: "POST",
url: "your file url to do database opration & fetch detail back to here",
data: cstring,
cache: false,
success: function(result) {
$('.resultdata').html(result)
}
});
});
});
</script>
<div class="resultdata"></div>

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

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.

jQuery fast mouse move mouseleave event triggers before previous event completes

If a users mouse goes over a table cell then a dropdown box replaces the html with data loaded via a post call. This works fine if the users mouse move is not too quick, but if it is too fast the html doesn't update so that when the user moves the mouse back in the html is incorrect.
$(".edit_dropdown").bind('mouseenter', function () {
$(this).unbind('mouseenter');
var a = $.trim($(this).html());
var id = $(this).attr('id');
$(this).html("<span id='s-" + id + "'></span>");
$.post('save/dropdown.php', {
id: id,
a: a
}, function (data) {
$("#s-" + id).html(data);
$(".edit_dropdown").bind('mouseleave', function () {
var id = $(this).attr('id');
var a = $("#e-" + id).val();
var dir = $(this).attr('class');
$(this).html(a);
$(this).bind('mouseenter', function () {
$(this).unbind('mouseenter');
var a = $.trim($(this).html());
var id = $(this).attr('id');
$(this).html("<span id='s-" + id + "'></span>");
$.post('save/dropdown.php', {
id: id,
a: a
}, function (data) {
$("#s-" + id).html(data);
});
});
});
});
});
html
<tr>
<td>customer county</td>
<td class="edit_dropdown" id="customer-cust_s_county"><?php echo $row['cust_s_county']; ?></td>
</tr>
The $.post file returns a list of UK counties, if the county name matches the html then that county is returned as the selected option.
The problem occurs because the mouseleave handler is only put in place in response to an asynchronous response to the mouseenter handler.
You should be looking for a simpler overall code structure that doesn't involve detaching and reattaching handlers.
It should be possible to write two handlers that remain permanently attached, as follows :
$(".edit_dropdown").on('mouseenter', function () {
//Perform all mouseenter actions here.
//If necessary, test for different states and branch as required.
}).on('mouseleave', function () {
//Perform all mouseleave actions here.
//If necessary, test for different states and branch as required.
});
Another point: As the list of counties is static, you can serve it once as part of the page's original HTML. You then need to return only the name or id of the county to be selected rather than repeatedly returning the whole list.

Categories