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

Django template alternative to the `with` tag

django django-templates

In Django templates, it is possible to introduce a new named variable to the context using the with tag:

OpenLayers Comparison Filter / Object Property

javascript openlayers

Is it possible / is there a workaround to compare a second level propety in OpenLayers.Filter.Comparison?

How to decorate a method in Ruby without alias_method_chain

ruby object-model

We all know, that if the target class is composed with modules, you can just call super in a new module. But what if it is an ordinary method in a class?