Follow us on Twitter!
One mans freedom fighter, another's terrorist.
Thursday, April 24, 2014
Navigation
Home
HellBoundHackers Main:
HellBoundHackers Find:
HellBoundHackers Information:
Learn
Communicate
Submit
Shop
Challenges
HellBoundHackers Exploit:
HellBoundHackers Programming:
HellBoundHackers Think:
HellBoundHackers Track:
HellBoundHackers Patch:
HellBoundHackers Other:
HellBoundHackers Need Help?
Other
Members Online
Total Online: 25
Guests Online: 23
Members Online: 2

Registered Members: 82895
Newest Member: kevy90
Latest Articles
View Thread

HellBound Hackers | Computer General | Programming

Author

AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 22-04-10 10:19
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
Code

<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---
Code

<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.



That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.

Edited by goluhaque on 22-04-10 13:10
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 22-04-10 13:07
Number of things here:

1. 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.

2. 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.

3. There's a floating pre tag in your markup that seems to be lost.

4. Get Firebug (if you don't already have it), and use the Console tab. It's great for troubleshooting AJAX.

5. 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.


Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 22-04-10 13:31
A null response. The alert shows nothing/NULL.
Sad


That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.

Edited by goluhaque on 22-04-10 13:38
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 22-04-10 13:40
Post the ready state function that you bound to the event. The one that generated the null alert.




Edited by on 22-04-10 13:41
Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 22-04-10 13:45
Code
xmlhttp.onreadystatechange=function()
  {
  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



That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.

Edited by goluhaque on 22-04-10 13:51
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 22-04-10 13:54
goluhaque wrote:
Code
xmlhttp.onreadystatechange=function()
  {
  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.


Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 22-04-10 13:57
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.
Code

<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);
}






That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.

Edited by goluhaque on 22-04-10 16:54
Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 24-04-10 12:37
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.


That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 24-04-10 15:03
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.


Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 24-04-10 15:11
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. Wink


That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.

Edited by goluhaque on 24-04-10 15:13
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 24-04-10 15:25
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. Wink

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().


Author

RE: AJAX Response problem

goluhaque
Member



Posts: 197
Location: India
Joined: 17.02.10
Rank:
Apprentice
Warn Level: 30
Posted on 24-04-10 15:31
define wrote:
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. Wink

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().

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.


That applause I receive from y'all on posting this post would have gotten me drunk on power if I hadn't already been high on life.
Author

RE: AJAX Response problem


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 24-04-10 15:34
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. Smile