This is to function in a similar way to slack. I need the page to update dynamically, in case the user is typing.
I have index.php, messages.html and newmessage.php
The chat page (index.php) looks like this:
<h1>Chat</h1>
<?php
echo file_get_contents("./messages.html") ;
?>
<br>
<form action="newmessage.php" method="post">
<input type="text" placeholder= "Compose a new message..." name="message" required>
<input type="submit"><br>
with the php looking like this in newmessage.php:
<?php
$message = $_POST["message"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "<hr>{$message} <br> from: {$_SERVER['PHP_AUTH_USER']} at: {$timestamp} <br><br> \n";
$file = fopen("./messages.html","a+ \n");
fwrite($file, $text);
fclose($file);
?>
<meta http-equiv="refresh" content="0.5;URL='/chat/index.php'"/>
<p>Sending Message...</p>
So messages show up to the user who sent the message, but not others in the chat. I can't use meta refresh in case other users are typing something and I've tried to make just the <?php echo file_get_contents("./messages.html") ; ?> refresh or use AJAX or event listeners. I need that contents to dynamically update once a new message is posted to messages.html.
Any pointers would be appreciated. Thanks in advance.
update because answer edit was rejected
function reloadData()
{
var now = new Date();
url = 'liveData?' + now.getTime();
try {
req = new XMLHttpRequest();
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
alert("No AJAX Support");
return;
}
}
}
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
function processReqChange()
{
// If req shows "complete"
if (req.readyState == 4)
{
dataDiv = document.getElementById('currentData');
// If "OK"
if (req.status == 200)
{
// Set current data text
dataDiv.innerHTML = req.responseText;
// Start new timer (1 min)
timeoutID = setTimeout('reloadData()', 60000);
}
else
{
// Flag error
dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
}
}
}
The best way to get the dynamic updating you are looking for would be AJAX, because you don't really want a real refresh all the time. You said, you tried AJAX? How did that approach look like?
My hint would be to get a basic understanding of web architecture. Try to understand the JS-code you found and how AJAX works. Did you work with JS before? If not, learn the basics.
Change the url variable to the url you use on your server to return the data. Yes, you will need that. Than look at the callback function (processReqChange()).
I would give you more than just hints, but in your early stage it is better to do a lot alone with some hints by more experienced developers.
Related
I have been looking for getting XML data into my html page for few days now, and I still can't make it work.
I followed many tutorials, but I can't find the simplest way, to just dump xml data in an html page.
My XML data is generated by a php script.
<exemple>
<data> Hello</data>
<data> World</data>
</exemple>
I have seen people using all kind of tech, like angular.js, and long script, but I feel like things are to complicated for just a simple "print".
I know PHP and I would just do an include or an echo do to that.
The easiest script I found (but cannot make it work) was this one :
function showGetResult( )
{
jQuery.ajax({
url: 'localhost/test/test.php',
type: 'get',
dataType: 'text/xml',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult();
My question is :
Can I really hope to make work a script as simple as that ?
Angular js would help me if my whole app is getting data from database using php-xml-ajax ?
I'm very new to ajax, so please be indulgent. Thank you very much
Well since stackoverflow is a place where people thumb down a question posted 5 min ago because they think it's dumb. (actually the only forum i know where you are afraid to post dumb question), I asked somewhere else and I managed to make a working script. Here is it.
I load an txt file when you click on the button.
function submitForm1()
{
var req = null;
document.getElementById("dyn1").value="Started...";
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
req.onreadystatechange = function()
{
document.getElementById("dyn1").value="Wait server...";
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById("dyn1").value=req.responseText;
}
else
{
document.getElementById("dyn1").value="Error: returned status code " + req.status + " " + req.statusText;
}
}
};
req.open("GET", "helloworld.txt", true);
req.send(null);
}
</script>
<form name="ajax1" method="POST" action="">
<p><input type="BUTTON" value="Envoyer" onclick="submitForm1()"></p>
<p>Reçu:
<input type="text" id="dyn1" size="32" value=""></p>
</form>
I'm working on ajax for the first time and I feel like I'm close to solving this problem but I need some help. I have my webpage file first below, that has an input field for an email address. When the user submits, the ajax doWork() function should be called which creates the request and processes the request. I have fixed the initial issue of the request being created so I'm positive that the correct object has been created based on the browser. My issue is there's no response text being submitted back and no email is created. The goal is for the user to enter the email, then an introductory email sent back to that address, when this is successful, a response string should be submitted back letting the user know that they have successfully been added to the mailing list and the submission has worked. Thanks for any help, it is greatly appreciated.
<?php include('../includes/educateHeader.php');?>
<script type="text/javascript" charset="utf-8" src="ajax.js"></script>
<div class="involve">
<h1>How to Get Involved In OEC</h1>
<span>Want to become more involved in Operation:Educate Children and don't know how? Share your email address with us, like our facebook page, or check out blog out to learn more about how you can join and help children obtain the education they deserve</span><br></br>
<form method="get">
Email: <input type="email" name="email" id="email" required><br></br>
<input type="submit" value="Send" onclick="doWork()">
</form>
</div>
<div id="outputResponse">
</div>
<?php include('../includes/educateFooter.php');?>
So here is the ajax.js file that creates the request and prints out the data recieved from the email.php file
function getHTTPObject() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput() {
if (httpObject.readyState == 4 && httpObject.status == 200) {
document.getElementById('outputResponse').value = httpObject.responseText;
}
}
function doWork() {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "email.php?email=" + document.getElementById('email').value, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
var httpObject = null;
Lastly here is the email.php script which should accept the ajax request and echo back whether a success has occurred or not.
<?php
if (isset($_GET['email'])) {
$mail = trim($_GET['email']);
$subject = 'Welcome!';
$message = 'Thank you for joining the Operation:Educate Children email list. In the future, we will send you updates about new opportunities to become more involved in the activities that we run here at OEC and you could make a difference on children\'s futures. Thank you and best wishes!';
mail($mail, $subject, $message);
echo 'Success! Thank you for your interest in Operaton:Educate Children. Stay tuned for updates!';
}
?>
First add return false; at the end of your function doWork and change onclick="doWork()" to onclick="return doWork()"
Then also change below line
document.getElementById('outputResponse').value = httpObject.responseText;
to
document.getElementById('outputResponse').innerHTML = httpObject.responseText;
Read this question too :) Setting innerHTML vs. setting value with Javascript
JQuery makes this really easy:
$.ajax({
url:'email.php',
type: "POST",
data: 'email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});
Or for GET, even easier:
$.ajax({
url:'email.php?email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});
I'm trying to put web notifications in the title/tab screen of my webpage. So whenever someone new says something and you're not on the tab, the will give notifications that you have a new message.
Is there any simple way to go about this?
Here's a live link of the chat
would i have to tamper with my post.php? or would
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'> C:\Users\<b>".$_SESSION['name']."></b> ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
or would i tamper with the input ?
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
thanks in advance for any help
!
I'd suggest you to have a look at the JavaScript function setInterval(). Make this function check for updates every x ms, if it finds any updates; edit the page-title.
Something like this should do the trick, tweak to get preferred result:
// This function will run every ~1s
setInterval(function() {
// Get the new data
$.post('post.php', function(data) {
// Handle the data
document.title = data;
});
}, 1000);
You should definitely add some error checking on the PHP-script (check if variables are set: isset($_SESSION['value'])), possibly at the javascript too.
see "document.title" in javascript.
var xarray = ['Someone Posted','Someone else posted'];
var i = 0;
function changeTitle(data){
document.title = data;
}
function changeEvery5Seconds()
{
i++;
i = i%2;
changeTitle(xarray[i]);
setTimeout("changeEvery5Seconds();",5000);
}
changeEvery5Seconds();
I have a flash movie that I need to read in a value from a PHP script in order to set which frame it starts from, I am using the following code:
if (loaded == total) {
var lvContent = new LoadVars();
lvContent.load("http://MY URL/Includes/getID.php");
trace("Who: " + lvContent.pageID);
lvContent.onLoad = function() {
if (lvContent.pageID != "29") { //If it's the home page then play the full animation. If not .. don't.
_root.gotoAndPlay(2);
}else{
_root.gotoAndPlay(90);
}
}
}
The problem is this is not working - it won't get into the load event. If I run the PHP manually I get "&pageID=29". If I debug this locally I get "Who: undefined" in the trace output window. From all the example I have read, I seem to be doing this correctly but it just doesn't seem to be working.
Flash: CS5 using Actionscript 2.0
Can someone take a look and let me know where I am going wrong please?
Thanks in advance.
You are defining the onLoad event after loading the contents. I don't think that can work.
Try
if (loaded == total) {
var lvContent = new LoadVars();
lvContent.onLoad = function() {
if (lvContent.pageID != "29") {
//If it's the home page then play the full animation. If not .. don't.
_root.gotoAndPlay(2);
}else{
_root.gotoAndPlay(90);
}
}
lvContent.load("http://MY URL/Includes/getID.php");
trace("Who: " + lvContent.pageID);
}
You're tracing pageID before it is loaded; try this
var lvContent = new LoadVars();
lvContent.onLoad = function(success:Boolean) {
if(!success) {
trace("Failed to load");
return;
}
trace("Who: " + lvContent.pageID);//trace from the onLoad handler
if (lvContent.pageID != "29")
_root.gotoAndPlay(2);
else
_root.gotoAndPlay(90);
}
lvContent.load("http://MY URL/Includes/getID.php");
I'm trying to begin learning AJAX, and I've already hit a little stump. So I'm starting simple and just trying to get an alert to pop up showing the length of the string the user types into a text field.
The HTML:
<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" onClick="check(this.form.email.value);"/>
</form>
The JS:
function check(email) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
email=encodeURIComponent(email);
req.open("POST","/scripts/addemail.php");
req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
req.send(email);
req.onreadystatechange=function() {
if(req.readyState==4) {
result = req.responseText;
alert("The length of the email is:" + result);
}
}
return false;
}
The PHP (addemail.php):
<?php
function check_email($input) {
return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>
And yes, I've included the JS in the section. I got this almost directly from a tutorial so I'm not sure what's going on. My testing browser is Safari, but I've also tried FF. Sorry is this is obvious, as this is my very first AJAX attempt. Thanks!
EDIT: Sorry, the problem is that its just going to the file described in action="addemail_fb" instead of the JS.
-iMaster
Change the onclick handler to onsubmit (on the form), like so:
<form onsubmit="return check(this.email.value);"> ... </form>
Also, set your req.onreadystatechange before calling req.send ()
inline javascript is bad practice. this solution may seem a bit more convoluted but if you implement it into the rest of your scripts then you will find this much more elegant.
JS libraries use similar methods, but if you cant use one then do this instead:
onDomReady(function(){
var oForm = document.getElementById("myform");
addListener(oForm,"submit",function(){
removeListener(oForm,"submit",arguments.callee);
// do stuff here
});
});
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.addEventListener) { // Standard
element.addEventListener(type, expression, bubbling);
return true;
} else if(window.attachEvent) { // IE
element.attachEvent('on' + type, expression);
return true;
} else return false;
}
// Cross-browser implementation of element.removeEventListener()
function removeListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.removeEventListener) { // Standard
element.removeEventListener(type, expression, bubbling);
return true;
} else if(window.detachEvent) { // IE
element.detachEvent('on' + type, expression);
return true;
} else return false;
}
function onDomReady(fn) {
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fn();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fn();
} else {
setTimeout( arguments.callee, 0 );
return;
}
});
} else {
// A fallback to window.onload, that will always work
addListener(window,"load",fn);
}
}
Here is the problem:
You are doing it wrong.
And jQuery is the Answer.
But seriously. Try using jQuery, as it will make you Javascript life easier than cutting into a piece of pumpkin pie.
AJAX is one of the most annoying subjects in Javascript, and jQuery, along with other libraries have gone and made the problem much easier to deal with. Plus, there are many many other great features of jQuery that just make it so much more wonderful to work with Javascript.
In jQuery, the entire code would look like:
$.post("/scripts/addemail.php", {email_address:email}, function(data){
alert("The length of the email is:"+data);
});
Speaking of pumpkin pie.....
Now that I've finished my public server announcement for jQuery, you will want to check the Javascript console (Ctrl + Shift + J in Firefox), and run the page. It will give you any errors that you are bound to have such as syntax errors or various other things that go wrong.
If you can go there and then give us any error messages that pop-up, we will be more likely to be able to solve your problem.