Implementing a Shoutbox with javascript and AJAX

I've looked at tons of demos and AJAX and JavaScript tutorials, but I can't seem to get this thing to work right. Here's what I've got...

function createRequestObject() {
var ro = false;
if (window.XMLHttpRequest) {             // Mozilla, Safari, ...            
    ro = new XMLHttpRequest();
} else if (window.ActiveXObject) {       // IE                              
    try {
        ro = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            ro = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) { }
    }
}
return ro;
}


function ajaxrequest(){
var http = createRequestObject();
if(http) {
    var name = "Strassburg";
    var message = "Strike three you're out";
    http.open('post', '/server/shout.php');
    // needed in order for most servers to see POST data                    
    http.setRequestHeader('Content-Type',
                          'application/x-www-form-urlencoded');
    http.onreadystatechange = function() {
        if(http.readyState == 4){
            if(http.responseText.indexOf(':' != -1)) {
                var data = http.responseText.split(':')
                alert(data)
            }
        }
    };
    http.send('name=' + name + '&message=' + message);
}

}

Right now I'm doing it with static text (name and message instead of using the user entered fields), but I just get an empty alert. If the readyState is set to 4 this means that the ajax call was successful I believe? the server/shout.php was given to me, I dont understand php very well, but if a snippit of that is needed I can put it here as well.

Answers


its this line http.responseText.indexOf(':' != -1)

( ":" != -1 ) = true, so indexOf is looking for true in the responseText

try this http.responseText.indexOf(':') !== -1


readyState == 4 means that request was completed, to check if it was OK check http.status == 200

if (http.readyState == 4) {
 if(http.status == 200) {
   alert(http.responseText);
 }
}

P.S. that should be a comment, but i don't have enough rating to comment your post


Need Your Help

WiX undefined preprocessor variable

preprocessor build-automation wix3 votive

I'm starting to use WiX in order to do automated builds to create msi's of my c# projects and am experiencing the error "Undefined preprocessor variable '$(var.MyProject.TargetDir)'"

How digg (or other high load category websites) are storing user sessions?

php session scalability high-load

How does digg or any other high-traffic website store user sessions? What do they use for storing the user sessions? File system, DB (which one?), memcache or both?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.