Show "Typing..." for web based chat application - javascript

I have almost completed my chat application using php & ajax functions .
Now question is , how to show "Typing.." (text) when the opposite user triggers the keyup() function from text-area.
My working structure :-
chat.php
<?php
// unique.html is created for each individual chat , just name is stored in database.
//For eg :- Two user_id's(5,4) combined together forming 54.html ..& so on
echo '<div id="mychat_box">
//old content of chat/messages are loaded from an unique.html file here ..
//working fine
</div>
<textarea id="usermsg" ><textarea>
<input type="submit" id="submitbutton">';
?>
Ajax functions
$('#submitbutton').click(function(){
$('#usermsg').val();
//Content is posted to post.php via ajax
//working fine
});
function Loadlog() {
// This function loads/refresh the contents
//(renders content from unique.html) inside the div mychat_box
via setInterval() , 10 seconds.
}
post.php
<?php
//content is accepted from the ajax call & posted to the unique.html file .
//also some information is collected & stored to database.
//Working fine
?>
Above process is working fine , last need is to to add "Typing.." text dynamically(ajax ?) when the opposite user triggers the keyup() function as asked earlier.
Can anyone explain how can it be achieved ? Or explain me the logic behind it with some pseudo-code/article/tutorial ?
Will post code in more detail if necessary.

Related

Resetting json file with button click

I have a todo list program and I want it to be reset to a predefined set of json within the json file once a button is clicked. For example, if the json file was full with data and someone clicked the button I want it to edit the json file to just say:
[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]
This is on cpanel latest using the latest stable php version. I've tried fwrite and file_put_contents but can't seem to get it working.
This is what I've tried already:
<html>
<h2>Click</h2>
<form action="" method="post">
<button name="click" class="click">Click me!</button>
</form>
<?php
if(isset($_POST['click']))
{
echo file_put_contents("test.json","[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]");
}
?>
</html>
When clicking the button nothing happens, no errors or anything?
You haven't assigned an action to the form, for this to work you should add the URL of the current page (so it redirects to itsself). Only then the post request is sent.
PHP won't run anything asynchronous: stuff only happens on page load.
You have syntax errors in your script - you have to escape the quotes in the string. Always look at the webserver error log or enable error display during development.
Here is the fixed code:
echo file_put_contents("test.json","[{\"completed\":false,\"task\":\"Kitchen - Sweep Floor\",\"important\":false}]");
You should use something like json_decode. Don't build json by hand:
$data = array(
"completed"=>false,
"task"=>"Kitchen - Sweep Floor",
"important"=>false
);
echo file_put_contents("test.json",json_encode($data));

How to run a PHP function due to a button click (with button 'data' passed)?

I know that AJAX could solve my issue. I need help how I can solve it in my specific case however. I manage some sortiment items on a page, they get displayed with a PHP script (checks the database, if the item is available, and if so, it gets displayed). I now want an admin page where I can kind of "toggle" via a sortiment table to display or not display an item (set it as available or non available.
What I need is: if the button is clicked, I would like to start a php-skript. There should be an value passed to that script (the button id). The script itself should open an SQL connection, change a DB value based on the passed ID of the button. Then close the connection. Optionally also refresh the table (or one value) from where the button was clicked.
Can someone help me, at least telling me what I need to do this? (jQuery, Ajax?). The passing of the ID would be important, else I'd need to do function for every button.
An table entry looks like this:
<tr>
<td>Himbeerhonig</td>
<td id="himbeerhonig">Ja</td>
<td><button type="button" id="himbeerhonig" onclick="function()">press me to execute function</button></td>
</tr>```
(possible PHP pseudocode)
open SQL connection
look for database entry based on the passed ID
change the value of the found entry (!currentValue)
close SQL connection
*optionally*
refresh the <td id="himbeerhonig"> with the updated value.
I appreciate any help very much! Just need some hints as to how to do it properly. It's just a concept that currenty is hard to grasp for me so far.
1- If you want to do this with ajax (without browser refresh), you should create a separate php file, and put your php scripts in there. it's called api (api has special format for output, so search create api in php if you want to do this). then on javascript, you should do an ajax call to that php address, on onclick event of button. and then javascript will return data and you can create elements based on that data.
2- however you can do this without ajax(it will refresh browser). just write your inline phps as you wrote :
<html>
<!-- your html codes-->
<?php
if($_GET['buttonClicked']){
//put your php codes here to run when button clicked
?>
<!-- you can even put html here, even it can be on php loop. -->
<?
}
<!-- your html codes-->
<!-- turn your button to a form-->
<form action="/" method="get">
<input name="buttonClicked" hidden value='1'>
<input type="submit" value="Submit">
</form>
</html>
it's as easy as this. when button clicked, a get request will send to current page, and php will handle it, for example it will render additional html elements to the page.

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Update content of div using javascript/jquery/php

I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];

rating button, one click to pass parameters and execute php

I'm somehow stuck when I'm working on:
I want to pass a parameter to a php file and execute it when we rate something. php file is finished, but don't know how to code js part.
In detail,
user rates a passage, js gets the rating;
------ get parameters, store them in function Rate(), finished
when user submits it;
------ don't know how to check if the button is clicked, add DomListener in Rate()?
js calls the php file meanwhile passing the rating parameter to it;
------ php part finished
execute the php file without opening it in a new window.
----- don't know what to do.
HTML
<div>
<form id="rateform" action="php/rate.php" enctype="text/form-data" method="POST">
<input id="rating" type="text" />
<input id="sbm" type="button" />
</form>
</div>
JS
function Rate(){
var rate = document.getElementById("rating").value;
var sbm = document.getElementById("sbm");
// don't know how to do...
//if(sbm is clicked) {
// execute rate.php...
//}
}
thx in advance.
Here's how I'd do it in jQuery (better than dealing with an XMLHttpRequest object):
$('#sbm').click(function() {
var rating = $('#rating').val();
/* Send request to PHP script. */
$.post('/url/to/script', { rating: rating }, function(resp) {
console.log('Response:', resp);
});
});
And your php script could be something like:
<?php echo 'Hey, I got this rating ' . $_POST['rating']; ?>
I'm not a PHP guy, though!

Categories

Resources