server crashes when i use onreadystatechange - ajax

I am trying to create a chat for my website.
To load the new data, i run a function every 1.5''.
If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.
When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).
I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?
function loadchat() {
xmllive.open('GET','live.php', false);
xmllive.send(null);
myelemen('dcdd').innerHTML = xmllive.responseText;
}
function loadchatv() {
xmllive.onreadystatechange=function() {
if (xmllive.readyState==4 && xmllive.status==200){
myelemen('dcdd').innerHTML = xmllive.responseText;
}
}
xmllive.open('GET','live.php', true);
xmllive.send();
Thank you for your answer, MMM. Since your response, i read about your suggestions.
(http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).
I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.
So, tell me please, what do you think about this solution (simplified):
/////////// html file //////////////
<script type="text/javascript" charset="utf-8">
var xmlff;
if (window.XMLHttpRequest) {
xmlff=new XMLHttpRequest();
} else {
xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}
function waitForMsg(){
xmlff.onreadystatechange=function() {
if (xmlff.readyState==4 && xmlff.status==200){
document.getElementById('messages').innerHTML = xmlff.responseText ;
setTimeout('waitForMsg()', 1000 );
}
}
xmlff.open('GET','msgsrv.php' ,true);
xmlff.send();
}
</script>
</head>
<body>
<div id="messages">
</div>
<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>
/////// php file ///////////
<?
do {
sleep(3);
$result = mysql_query("SELECT message FROM chat ");
while ($row = mysql_fetch_array($result)){
$msg .= $row[0];
}
} while (mysql_num_rows($result) == 0);
header("HTTP/1.0 200");
print $msg;
?>
Thanks in advance.

Related

Ajax - understanding of the code

I try to understand Ajax. I'd like to understand how the data and commands flow in the code. I have the following code. Please, read my comments in this code. The comments describe, how I understand the code. The problem is marked as PROBLEM!!! Important notice: The code is working, I only try to understand the code.
<!DOCTYPE html>
<HTML>
<HEAD>
<META charset="UTF-8" />
<TITLE>Test02</TITLE>
</HEAD>
<BODY>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<SCRIPT>
function loadDoc() {
// select right object
function createXhttp(){
var variable;
if (window.XMLHttpRequest) {
// code for modern browsers
variable = new XMLHttpRequest();
} else {
// code for IE6, IE5
variable = new ActiveXObject("Microsoft.XMLHTTP");
}
return variable;
}
var xhttp = createXhttp();
// check the state
xhttp.onreadystatechange = function (){
// if the response is ready and file or url exists
if (xhttp.readyState == 4 && xhttp.status == 200) {
/* display the text in console - but which text if xttp.open
with source file is opened on the next line? (PROBLEM!!!)*/
console.log(xhttp.responseText);
}
};
// use method get and load the content of ajax_info.txt
xhttp.open("GET", "ajax_info.txt", true);
// send the request above
xhttp.send();
}
</SCRIPT>
</BODY>
</HTML>
Thank you for your advice.
but which text if xttp.open with source file is opened on the next line?
Let's take another example.
document.getElementById('some_button').onclick = function () {
console.log(document.getElementById("some_text_box").value);
}
It doesn't matter if the user hasn't typed anything in some_text_box at this point, because the function won't run until some_button is clicked.
Now back to XHR:
xhttp.onreadystatechange = function (){
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
… it doesn't matter that the request hasn't been sent yet, because the function won't run until the response arrives.
(OK, it will run every time the ready state changes, but the if statement means the meat of it won't run until the response arrives).

How to send data to 'post.php' using AJAX? (without Jquery)

I'm newbie on this webdeveloper matters. I have already made a form where i've used Ajax (JQuery lib) to create a chat box.
Now, i wanna try to do something similar without using Jquery to understand how Ajax works. First i just want to write my messages on log.html using AJAX, so then i can read them later. But i dont understand why i can't send my textarea data into post.php.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Teste</title>
<script type="text/javascript">
function sendXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var message=document.getElementById('msg').value;
xmlhttp.open("POST", "post.php", false);
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 0 ) {
alert("UNSENT");
}
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
xmlhttp.send(message);
}
</script>
xmlhttp.send(data) : Why im not sending my data to post.php?
Post.php is where i write my log.html (but i cant send my messages and i dont understand why):
<?php
$text = $_POST['message']; // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
fclose($fp);
?>
And this is my form.html
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc();">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit" value="Send"/>
</form>
</body>
have you taken a look at this link ?
It seems to have a complete explanation on how to build an AJAX request with PHP and MySql.
EDIT:
The problem in your code is both on your post.php, which has incorrect syntax (lacking double quotes before the last <br>), and should be something like :
post.php
<?php
$text = $_POST['message'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".stripslashes(htmlspecialchars($text))."<br>\n</div>\n");
fclose($fp);
?>
and with the request header, which should have the content-type set (see code below)
I based this answer on w3.org.
The final html here presented shall help you understand how Ajax requests behave on different browsers. Try it out.
It seems though that for Firefox to load the request, you need to do something when the Status is OPENED (1), and I don't quite understand why.
Try this code on different browsers to see the different approaches to XMLHttpRequest.
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function sendXMLDoc(obj){
var message=obj["message"].value;
var data = "message=" + message;
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
url = "http://localhost/AjaxPhp/post.php"
xmlhttp.open("POST", url , true);
xmlhttp.onreadystatechange = display_data;
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
function display_data() {
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
}
</script>
</head>
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc(this);">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit"/>
</form>
</body>
</html>
I don't truly understand the whys, but according to w3, the order of the requests should, in my understanding, be :
OPENED (after invoking the open method), HEADERS_RECEIVED (after setRequestHeader), LOADING (request body received). DONE (Data transfer completed, after send) .
Chrome handles the post.php but doesn't present any alert box (maybe its my popup settings, maybe not)
IE shows only the OPENED alert message
Firefox goes "Headers Received", "Data transfer completed","OPENED", "Data transfer completed".
Hope this helps understanding it a little bit more. Always go check w3.org for the ultimate source on the web. It might not be very user-friendly and intuitive, but provides some tips on the whys and the shoulds.

AJAX not working with XAMPP or is it just impossible

I'm still relatively new to AJAX and am trying to figure out why my simple test is not working. From what I read AJAX will not work under one domain, and other words pop up like cross-site and remote server. Anyways my problem is is that I'm not sure if my code is wrong or simply what I'm trying to do is impossible. I created a simple ajax request to submit data when I click on the button. Here is the code for the first script.
<html>
<head>
<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>
</head>
<body>
<input type="submit" onclick="load('adiv', 'hello.php');">
<div id="adiv"></div>
</body>
</html>
Here is the code for the file hello.php
<?php
echo 'aaa';
?>
AJAX is just an http request done in the background. But yes, there are security restrictions that prevent you doing a normal ajax request to any arbitrary server.
What your code is missing is actually setting the URL that you're placing the request to. You've got hello.php as a parameter to your load() function, but you never actually USE it. So you're doing an AJAX request to... "nowhere".

use of ajax in django problem with the code

I am new to ajax and using Django for web development.
Now My Template contains : sample.html
<html>
<body>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "/showtime/", true);
ajaxRequest.send(null);
}
</script>
<form name='myForm'>
Name: <input type='text' onBlur="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
In views.py my function is :
def showtime(request):
string = "Ajax Application"
data = {"string" : string}
pprint (data)
return render_to_response("sample.html",data)
Now, The output is not as expected . The template does not receives the response sent by the server
What is wrong with the code ?
If you're trying to populate the text-field with AJAX returned string, you should not use render_to_response. Just return the string.
def showtime(request):
s = "Ajax Application"
print "Returning %s"%s #is this line executed?
return HttpResponse(s, mimetype="text/plain")
try if /showtime/ works as expected when you type in your browser!
using a js framework like jquery will save you time and energy implementing ajax stuff, eg. see this tutorial http://lethain.com/entry/2007/dec/11/two-faced-django-part-5-jquery-ajax/
there are also some django-built-ins that you can use, eg request.is_ajax to verify if the request is really comng from ajax!

AJAX script not working in Firefox

I have written an AJAX script to read information from a database and inject it into a .php file as HTML. It works in IE8, Safari, Chrome but not Firefox. No errors displayed or anything, it just doesn't execute at all.
Here's the code:
function queryDatabase(query)
{
alert();
var xmlhttp;
if (window.XMLHttpRequest)
{
alert();
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
alert();
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "<center><span style=\"color: #ff7e00; font-size: 30px;\">LOADING...</div></center>";
}
}
xmlhttp.open("GET",query,true);
xmlhttp.send(null);
}
(The alerts were for testing purposes but none of them show up in Firefox)
Here's the divs it's used on:
<div onClick="queryDatabase('latestquery.php')" style="cursor: pointer;">TEST</div> <div onClick="queryDatabase('testtagquery.php')" style="cursor: pointer;">TEST</div>
Any help is appreciated :)
Thanks
Sam
Well for a start you can't do alert() in Firefox - the argument isn't optional. Change it to alert(0) and see what happens the.
Secondly, I don't see where you set content - is that a global variable you've got initialised somewhere?
You can check for script errors in Firefox by bringing up the Error Console (Tools -> Error Console or Ctrl + Shift + J).
To help even more, install firebug.
Edit: if content is just the id of an element you need to do document.getElementById(content).innerHTML = ...;
The best advice I can give you is to start using a javascript framework that implements the AJAX functionality for you and makes it much easier to write code using it.
Using jQuery this would look like:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</script>
<script type="text/javascript">
$(function() {
$('#div1').click( function() {
queryDb(this,'lastestquery.php');
});
$('#div2').click( function() {
queryDb(this,'testtagquery.php');
});
});
function queryDB(div,url) {
$(div).load( url );
}
</script>
<div id="div1" style="cursor: pointer;">TEST</div>
<div id="div2" style="cursor: pointer;">TEST</div>
Note that I would probably also use a CSS class to assign the cursor as well.
<div id="div1" class="clickable">TEST</div>
Loaded via a CSS file
.clickable {
cursor: pointer;
}
Here's the lastquery.php file if this helps:
<?php
$con = mysql_connect("localhost","root","***");
mysql_select_db("main", $con);
//GET MOST RECENT POST ID
$last_id_query = mysql_query("SELECT * FROM articles");
$last_id_result = mysql_fetch_array($last_id_query);
$last_id = (int)$last_id_result['id'] - 2;
//USE MOST RECENT POST ID TO GENERATE LAST 5 ARTICLES SUBMITTED
$result = mysql_query("SELECT * FROM articles WHERE id > '$last_id' ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
echo "<div id=\"centralcontent\"><div class=\"articleheading\"><strong>".$row['title']."</strong></div><div class=\"tag\"> in ".$row['tag']."</div><div class=\"articleinfo\">".$row['date']."</div>";
echo "<div class=\"articlecontent\">".$row['content']."</div></div>";
}
mysql_close($con);
?>
Edit: This worked on the face of it, but it looks now like it was not the actual solution.
Taking your code above and moving the xmlhttp.open call to before you set the state change function worked for me. Like this:
xmlhttp.open("GET",query,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "..";
}
}
xmlhttp.send(null);

Resources