AJAX Response problem
I was trying to create a ShoutBox kind of thing using AJAX/PHP/MySQL. The problem I am facing is that the JAVAScript part is not accepting the response of the PHP part. There is no change in the section where the previous shouts are to be printed. What's the problem. Also it looks like the JAVASCRIPT part is not sending the data correctly as whatever I put in the form is not inserted in the SQL. Instead, to make a change, I have to go to the PHP page and put the variables as GET comments myself.
Here is the code–– HTML/JavaScript/AJAX part
<html>
<head>
<script type="text/javascript">
function showSHOUT()
{
var str = document.shoutform.shout.value;
var name = parseInt(document.shoutform.name.value);
var url="shouts.php";
url=url+"?q="+str+"&name="+name;
url=url+"&sid="+Math.random();
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="shoutform" onSubmit="return showSHOUT()">
<center>Name:<input type="text" name="name" /><pre> </pre>
Shout:<input type="text" name="shout" /><br />
<input type="Submit" value="Shout!">
</form>
</center>
<p><div id="myDiv">Previous Shouts:<br /></div></p>
</body>
</html>
The PHP part is here—
<html>
<body>
<?php
$shout=$_GET["shout"];
$name=$_GET["name"];
if($name=="")
{
echo("No name!");
}
else
{
if($shout=="")
{
echo("stupid");
}
else
{
$con = mysql_connect('<SQL Server Name>', '<User Name>', '<password>');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("<database name>", $con);
mysql_query("INSERT INTO shouts (Username, Shout) VALUES ('$name', '$shout')");
$result=mysql_query("SELECT * FROM shouts");
echo("<table border='10'>");
echo("<tr><th>Username</th><th>Shout</th></tr>");
while($row=mysql_fetch_assoc($result))
{
echo("<tr><td>" . $row['Username'] . "</td>");
echo("<td>" . $row['Shout'] . "</td></tr>");
}
echo("</table>");
}
}
?>
</body>
</html>
The PHP part(i.e. inserting data in the database and then outputting it) is working properly.
Number of things here:
-
Your PHP script has html and body tags in it, which would also get returned in your response. You don't want those in a div's innerHTML. Take those out.
-
You start assigning to xmlhttp before you define it, so slap a var statement above the if conditional that creates it. The key to making something work cross-browser is doing the right way, even if you know you can get by without it sometimes.
-
There's a floating pre tag in your markup that seems to be lost.
-
Get Firebug (if you don't already have it), and use the Console tab. It's great for troubleshooting AJAX.
-
Alert the responseText in the readystate callback, and see if you get an alert. If you do, it's probably #1 on this list that will fix it. If you don't, then try taking out .status==200 or changing .readyState==4 to .readyState>=3.
{
if (xmlhttp.readyState>=3)
{
alert(xmlhttp.responseText);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}```
Not sure if you were asking for this. Anyway, here it is, I think.
Also, Firebug's giving this error -
> [Exception... "Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE) [nsIJSCID.getService]" nsresult: "0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE)" location: "JS frame :: file:///C:/Users/golu/AppData/Roaming/Mozilla/Firefox/Profiles/zbweozg1.default/extensions/%7Be0204bd5-9d31-402b-a99d-a6aa8ffebdca%7D/components/ignore-history.js :: anonymous :: line 98" data: no]
file:///C:/Users/golu/AppData/Roaming/Mozilla/Firefox/Profiles/zbweozg1.default/extensions/%7Be0204bd5-9d31-402b-a99d-a6aa8ffebdca%7D/components/ignore-history.js
Line 98
goluhaque wrote:
{
if (xmlhttp.readyState>=3)
{
alert(xmlhttp.responseText);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}```
Make it > 3 instead of >= now. And, yeah, that's what I wanted to see.
> [Exception... "Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE) [nsIJSCID.getService]" nsresult: "0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAILURE)" location: "JS frame :: file:///C:/Users/golu/AppData/Roaming/Mozilla/Firefox/Profiles/zbweozg1.default/extensions/%7Be0204bd5-9d31-402b-a99d-a6aa8ffebdca%7D/components/ignore-history.js :: anonymous :: line 98" data: no]
file:///C:/Users/golu/AppData/Roaming/Mozilla/Firefox/Profiles/zbweozg1.default/extensions/%7Be0204bd5-9d31-402b-a99d-a6aa8ffebdca%7D/components/ignore-history.js
Line 98
Ignore this. It's something local to your machine.
Same Result.
EDIT: Did it. Here's the new JS code. Honestly speaking, I can't spot any difference except the fact that I used more variables. And yes, the idea came directly from seeing one of those codes at Tizag.
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
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){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var name = document.getElementById('Name').value;
var shout = document.getElementById('Shout').value;
var queryString = "?name=" + name + "&shout=" + shout;
ajaxRequest.open("GET", "shouts.php" + queryString, true);
ajaxRequest.send(null);
}
I want to auto-refresh the part that's showing the shouts as soon as everybody enters another shout, any tips? Do I have to find the length of the array ( as in $rowwhatever=mysql_fetch_assoc($resultwhatever) ) by a simple counter ( c1=c1+1 ) everytime in the while loop and store that in a database itself or what? Any tips?
P.S.I know the topic's somewhat different but it felt like a waste of place to create another thread for a related problem.
Weird. I don't see much different about the AJAX bit except that the IE portion is more flexible.
goluhaque wrote: I want to auto-refresh the part that's showing the shouts as soon as everybody enters another shout, any tips? Do I have to find the length of the array ( as in $rowwhatever=mysql_fetch_assoc($resultwhatever) ) by a simple counter ( c1=c1+1 ) everytime in the while loop and store that in a database itself or what? Any tips?
You can't truly refresh the part showing the shouts every time one comes in… but, you can get pretty darn close. Javascript has setTimeout and setInterval for a period of time to pass before performing an action; you could tie that into an AJAX call that retrieves any new posts and appends them.
You need to pull the datetime or id of the last shout from the shout area, then send that along with your AJAX call so you can check for results.
Also, you can set it up so that it checks for new posts when a person posts a new post. That is, in the browser of the person that posted the new post, check for updates right after that.
I don't use that method. I use a more time consuming one. The script does not check for new values but prints the whole table when the user enters a shout. Instead, it outputs the whole table everytime an AJAX response comes in.
Also, that new JS code, such strange things have been happening to me lately. In PHP, isset was not working(and there was no syntax/logic problem). Had to resort to =="" . Heh. Some fucking ghost, probably. ;)
goluhaque wrote: I don't use that method. I use a more time consuming one. The script does not check for new values but prints the whole table when the user enters a shout. Instead, it outputs the whole table everytime an AJAX response comes in.
That's terribly inefficient. I'd consider that a high-priority for refactoring before you actually use this anywhere.
You should only be appending the new shouts. Also, if you're not resending the entire shout log via AJAX each time, then your AJAX responses will be faster and you'll put less load on your DB.
goluhaque wrote: Also, that new JS code, such strange things have been happening to me lately. In PHP, isset was not working(and there was no syntax/logic problem). Had to resort to =="" . Heh. Some fucking ghost, probably. ;) That's a common misunderstanding in PHP. It's not that the JS code is breaking your PHP… it's the fact that your PHP is a bit incorrect.
isset() is used to test if a variable exists. empty() is used to test if a variable has a non-zero integer or non-empty string, or is not null.
Use !empty().
define wrote: [quote]goluhaque wrote: I don't use that method. I use a more time consuming one. The script does not check for new values but prints the whole table when the user enters a shout. Instead, it outputs the whole table everytime an AJAX response comes in.
That's terribly inefficient. I'd consider that a high-priority for refactoring before you actually use this anywhere.
You should only be appending the new shouts. Also, if you're not resending the entire shout log via AJAX each time, then your AJAX responses will be faster and you'll put less load on your DB.
goluhaque wrote: Also, that new JS code, such strange things have been happening to me lately. In PHP, isset was not working(and there was no syntax/logic problem). Had to resort to =="" . Heh. Some fucking ghost, probably. ;) That's a common misunderstanding in PHP. It's not that the JS code is breaking your PHP… it's the fact that your PHP is a bit incorrect.
isset() is used to test if a variable exists. empty() is used to test if a variable has a non-zero integer or non-empty string, or is not null.
Use !empty().[/quote] Heh.I was not saying that the JS code was bugging my PHP script. that was a separate incident. Anyway, thanks for pointing out the empty() and isset(). My script was really incorrect.
goluhaque wrote: Heh.I was not saying that the JS code was bugging my PHP script. that was a separate incident. Anyway, thanks for pointing out the empty() and isset(). My script was really incorrect. Yeah, I more meant that the misconception was regarding isset() vs. empty(). A lot of people use those incorrectly.
Welcome. :)