I have made a simple chat script using jquery and AJAX but the huge hole in it is that i can only chat with myself properly :P
heres the javascript for my main file
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#status").load('ajaxLoad.php');
$("#userArea").submit(function(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var name = '<?php echo $name; ?>';
var url = "ajaxPost.php";
var msg = document.getElementById("messages").value;
var vars = "messages="+msg+"&id="+id+"&name="+name;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
$("#status").append(return_data);
}
}
hr.send(vars);
return false;});
});
and heres my 2nd file "ajaxLoad.php"
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT messages,id FROM chat");
while($row = mysql_fetch_array($sql))
{
echo $row["messages"];
}
?>
Now what i need is to continually refresh "ajaxLoad.php" so that users can chat in realtime without refreshing the page...any way around this?
// reload every second
setInterval(function() {
$("#status").load('ajaxLoad.php');
}, 1000);
Be careful of making too requests to the server. It's going to be rather intensive.
You can use javascript setInterval to call your php script every x seconds.
https://developer.mozilla.org/en/window.setInterval
If you want to get bleeding edge, you should look into WebSockets.
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable.
Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.
<?php
set_time_limit(0);
while(true)
{
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
echo $jsonContent;
sleep(10);
}
?>
And here my javascript code.
setInterval(function(){
var jsonUpdPostData = <?php echo $jsonContent; ?>;
}, 100);
What should i do to make it work? Any suggestion will be appreciated.
You can make it work this way:
getContent.php
<?php
echo file_get_contents('http://megarkarsa.com/gpsjson.php');
xxxx.js
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText); // this contains the new file contents
}
}
xmlhttp.open('GET', 'getContent.php');
xmlhttp.send();
}, 100);
I am trying to load a php file after a while by using ajax. What I am trying to do is kind of a quiz. I want an image screen to be seen by user for 3 seconds and then the answer choices to be seen. I want to do this for 3 or 4 times in a row. For example;
1)The question image
after a few seconds
2)Answer Choices
After click on an answer
3)Second question image
... and go on with this order.
I can do this with below code:
<script type="text/javascript">
var content = [
"<a href='resim1a.php'> link 1 </a>",
"<a href='resim2a.php'> link 2 </a>",
"insert html content"
];
var msgPtr = 0;
var stopAction = null;
function change() {
var newMsg = content[msgPtr];
document.getElementById('change').innerHTML = 'Message: '+msgPtr+'<p>'+newMsg;
msgPtr++;
if(msgPtr==2)
clearInterval(stopAction);
}
function startFunction() { change(); stopAction = setInterval(change, 500); }
window.onload = startFunction;
</script>
<div id="change" style="border:5px solid red;width:300px; height:200px;background-Color:yellow"> </div>
But, when this file is included by another file, this script does not work. How can I make it work?
<script type="text/javascript">
function load(thediv, thefile){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile , true);
xmlhttp.send();
}
</script>
The previous page script is above. I use this script with the below code:
<div id="anotherdiv" >
<input type="image" onclick="load('anotherdiv' , 'include.php');"src="buton1.png">
</div>
The reason is because you are expecting the window to fire onload event:
window.onload = startFunction;
Window is loaded when the ajax is running, so why not call the function directly?
startFunction();
If you need some DOM elements before the script, just put the script below the DOM elements and the script will run after the DOM is ready.
you need to remove change(); from function startFunction()
here is the full example click here
I hope it will help for you.
I have a php page(calendar.php) which is using javascript to load a php calendar(calendar_start.php) and display the calendar in the center of the page.
I am trying to obtain a variable on the calendar_start.php page, however I cannot access variable which I am able to access from the calendar.php page.
below is one of the scripts used on calendar.php to generate canendar_start.php:
<script language="javaScript" type="text/javascript">
function initialCalendar(){
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
showmonth = month;
showyear = year;
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
and below is part of the page calendar.php where I am generating the calendar:
<body onLoad="initialCalendar(<?php $_GET['page']; ?>);">
I am unable to grab the variable on calendar_start.php and I would really appreciate any help.
Kindest Regards,
Ryan
EDIT::
This may be helpful, this is the error when I am trying to display the variable on calendar_start.php
Notice: Undefined index: page in C:\wamp\www\project\calendar_start.php
Change $_GET['page'] to $_REQUEST['page'].
$_REQUEST combines $_GET and $_POST together (with $_POST taking precedence). That way you won't have to worry about backward comaptibility if you change it in the future.
It is, however, a bad idea to echo ANY of these variable unsanitized to users browser.
EDIT:
Although your main problem is that you forgot the "echo" command in front of the variable.
I have a php page which is using javascript to produce a calendar on the page. I am trying to pass a variable so that I can reference it on the loaded page.
Below is the script I am using to generate the calendar(along with several others)
<script language="javaScript" type="text/javascript">
function initialCalendar(){
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
showmonth = month;
showyear = year;
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
and below is the way I am displaying this onto the php page:
<body onLoad="initialCalendar();">
I have tried using '<?php echo $page; ?>' and '<?php $_POST['$page'] ?>' in the brackets of initial calendar()
however I am having no luck, I hope I have explained correctly and in enough detail to make sence, however if you need anything more please just comment
Thanks,
Ryan
I don't know the layout of your $_POST array, but if I understood the question right you should try:
<body onLoad="initialCalendar('<?php echo $_POST['page'];?>');">
and change your function declaration to:
function initialCalendar(page){
Note that I've used single quotes ' around the value which PHP outputs. This to ensure that it didn't break anything if the value is a string.
Since you are passing variable through parameters like
localhost/project/calendar.php?page=something
use $_GET['page'] rather than the $_POST